且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理打字稿中异步函数的返回值?

更新时间:2022-05-10 03:15:19

对于 typescript Promise,你可以这样工作:

For typescript Promise, you can make it work this way:

public async initData (selectedCaseId: number): CaseBook {       
    return await this.casesService.GetCaseById(selectedCaseId);
}

但是由于您的 this.casesService.GetCaseById 是一个 Observable,您可能无法直接从它返回纯值.而是返回一个 Observable.

but since your this.casesService.GetCaseById is an Observable, you may not possible to return pure value from it directly. return an Observable instead.

public initData (selectedCaseId: number): Observable<CaseBook> {   
   return this.casesService
    .GetCaseById(selectedCaseId);
}

然后你可以用 async 管道为 angular2 绑定它:

and then you can bind it for angular2 with async pipe:

{{this.initData() | async}}

为了更好的性能,建议为它绑定一个值,例如:

for better performance, suggest to bind a value for it, for example:

ngAfterViewInit() {
    this.initData().subscribe( data => this.caseBook = data );
}