サービスクラスにある関数を呼び出そうとしていますが、その関数がデータを返すと、真偽値が真になります。 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に設定されます。
多くのご協力ありがとうございました。
あなたは 'this.service.getRecords()とはどういう意味ですか? 'getRecords()'の戻り値が 'undefined'(おそらく)か、' this.service'が未定義であることを意味しますか? 'this.service'はどこから来たのですか? (どこに設定されていますか?) –
getRecordsは私のservice.ts内の関数で、学生のリストを返します。今はそれが動作し、私がそれを呼び出すと、学生のリストが返されます。 getRecordsが正常に実行されたときに属性値を変更したいのですが、この目的のためにthis.service.getRecords()を追加しました(function(){console.log( "success getRecord"); this.loading = false;}、 function(){console.log( "失敗したgetRecord"); this.loading = true;});私は定義されていないオブジェクトで.thenを使うとエラーが出ます。 –
サービスがデータを返すときに何かをする方法を探しています。私はthis.service.getRecords()を呼び出すとレコードが返されますが、私の質問はサービスからレコードを返すとどうしたらいいですか? –