如何处理打字稿中异步函数的返回值? [英] How to handle the return value of async function in typescript?

查看:26
本文介绍了如何处理打字稿中异步函数的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

casesService 函数处理 HTTP 请求和响应并返回单个对象.我想返回对象.但由于它是一个异步功能,它返回空对象(this.caseBook).我希望它只有在它具有价值后才返回对象.

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

推荐答案

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

这篇关于如何处理打字稿中异步函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆