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

耗尽温柔 提交于 2019-12-31 05:19:10

问题


The casesService function handles a HTTP req and response and returns a single object. I want to return the object. But since it is an async functionality it returns empty object(this.caseBook). I want it to return the object only after it has value.

public initData (selectedCaseId: number): CaseBook {   

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

            this.caseBook = data;

        });
       return this.caseBook; 
 }

回答1:


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

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

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

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


来源:https://stackoverflow.com/questions/45413433/how-to-handle-the-return-value-of-async-function-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!