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

How to handle the return value of async function in typescript?

caseService 函数处理 HTTP 请求和响应,returns 是单个对象。我要return这个对象。但由于它是一个异步功能,它 return 是空对象 (this.caseBook)。我希望它 return 只有在它具有价值后才成为对象。

public initData (selectedCaseId: number): CaseBook {   

       this.casesService
        .GetCaseById(selectedCaseId)
        .subscribe(data => {

            this.caseBook = data;

        });
       return this.caseBook; 
 }

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

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

但是因为你的 this.casesService.GetCaseById 是一个 Observable,你可能无法直接从它 return 获得纯值。 return 改为 Observable。

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

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

{{this.initData() | async}}

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

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