2016-10-05 4 views
0

서비스 클래스에있는 함수를 호출하려고하는데이 함수가 데이터를 반환하면 하나의 부울 변수가 true를 설정합니다. student.ts 및 service.ts :angular2에서 동기 약속을 만드는 방법

// student.ts

public ngOnInit() { 
     this.config.load().then(() => { 

     this.service.getRecords().then(
     function() { console.log("success getRecord"); 
         this.loading = false; }, 
     function() { console.log("failed getRecord"); 
         this.loading = true; }); 

    }); 
    } 

//service.ts 지금에 의해

public getRecord(id: number): Promise<T> { 
      return this.getRecordImpl(); 

     } 

private getRecordsImpl(): Promise<T[]> { 




     let url = this.serviceUrl; 

     return this.http.get(url, this.getRequestOptionsWithToken()) 
      .toPromise() 
      .then(res => { 
       this.records = this.extractData<T[]>(res); 
       for (var i = 0; i < this.records.length; i++) { 
        var record = this.records[i]; 
        this.onRecord(record); 

       } 

       return this.records; 

      }) 

      .catch(this.handleError); 

    } 

, 서비스의 레코드 나는 bollow로 2 개 클래스가 반환하지만, this.service.getRecords(); 정의되지 않았습니다. 나는 성공 및 실패 작업을 처리하기 위해

그 때는

을 사용할 수 없습니다. 동기식으로 만드는 것이 좋지 않다는 것을 알고 있습니다. 비동기로 인해 getRecords가 정의되지 않게됩니다. 이를 처리하기위한 솔루션은 무엇입니까? 순차적으로 실행하고 싶습니다. 서비스가 레코드를 반환하면 변수는 false로 초기화되고, 그렇지 않으면 true로 설정됩니다.

도움과 가이드를 보내 주신 것에 대해 감사드립니다.

+0

당신은'this.service.getRecords()에 의해 무엇을 의미합니까? 'getRecords()'의 반환 값이'undefined' (있을 법하지 않음)이거나'this.service'가 정의되지 않았 음을 의미합니까? 'this.service'는 어디에서 왔습니까? (어디에 설정합니까?) –

+0

getRecords는 내 service.ts에있는 함수로 학생 목록을 반환합니다. 지금까지는 그것이 작동하고 내가 그것을 부를 때, 학생들의 목록이 반환됩니다. getRecords가 성공적으로 실행될 때 속성 값을 변경하려고합니다.이 목적을 위해 this.service.getRecords()를 추가했습니다. (function() {console.log ("success getRecord"); this.loading = false;}, function() {console.log ("실패한 getRecord"); this.loading = true;}); 하지만 정의되지 않은 개체에서 .then을 사용하면 오류가 발생합니다. –

+0

나는 서비스가 데이터를 반환 할 때 뭔가를 할 방법을 찾고있다. 내가 this.service.getRecords() 호출하면 레코드가 반환됩니다,하지만 내 질문에 서비스에서 레코드를 반환 한 후 어떻게 할 수 있습니까? –

답변

0

당신의 aproach가 올바르지 않다고 생각합니다. 무엇이 포인트를 약속하는 동기입니까? 당신이 정말로 이것을 원한다면 나는 당신이 Synchronous programming with es6 generators을 파고들 것을 제안하지만 보통 일은 많이 피곤합니다.

코드에서 귀하가 서비스에서 .then()을 첨부하여 약속을 소비하고 있음을 확인했습니다. 이 방법으로 새로운 약속을 만들어야합니다.

private getRecordsImpl(): Promise<T[]> { 
let url = this.serviceUrl; 
return new Promise((resolve, reject) => { 
    this.http.get(url, this.getRequestOptionsWithToken()) 
    .toPromise() 
    .then(res => { 
     this.records = this.extractData<T[]>(res); 
     for (var i = 0; i < this.records.length; i++) { 
     var record = this.records[i]; 
     this.onRecord(record); 

     } 
     resolve(this.records); 
    }) 
    .catch(this.handleError); 
}) 
} 

그리고 당신의 코드를 사용

:;``undefined`가

this.service.getRecords().then(
    function (records) { console.log("success getRecord"); 
        this.loading = false; }, 
    function (err) { console.log("failed getRecord"); 
        this.loading = true; }); 
관련 문제