Search code examples
javascripttypescriptangular2-services

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


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

Solution

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