2016-10-05 8 views
0

サービスクラスにある関数を呼び出そうとしていますが、その関数がデータを返すと、真偽値が真になります。 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();定義されていません。そして、私は成功と失敗のアクション処理するため

.then

を使用することはできません。 私はそれを同期させることは良い考えではないことを知っています。非同期であると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()を付けてPromiseを消費していることがわかります。このようにして、新しいPromiseを作成する必要があります。

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; });