Search code examples
angularasync-awaites6-promise

Return value of promise from service to component


I have a service class as follows

import { RetrieveMultipleResponse } from 'xrm-webapi/dist/models';

@Injectable()
export class CrmService {

   headers: any;
   error : any;
   store : Observable<any>;

   constructor(public crmDataService : CrmDataService) {}

   retrieveAllTeams(): Promise<RetrieveMultipleResponse> {
       return retrieveMultiple(this.crmDataService.config,"teams",null);
   }

}

And I'm calling it in the component like that:

load() {
    this.crmService.retrieveAllTeams()
        .then((results) => {
            if(results.value !== undefined && results.value !== null) {
                var teams = results.value;
            }
        },
        (error) => {

        });
}

So the retrieveAllTeams returns a Promise of type RetrieveMultipleResponse. The interface looks like that:

export interface RetrieveMultipleResponse {
    value: Entity[];
    '@odata.nextlink': string;
}

I would like to avoid using nested promises in my component so I am using Angular 6. I've tried to use async and await but I can't really figure out how to get results and the error from the retrieveAllTeams method in my component.


Solution

  • I would like to avoid using nested promises in my component so I am using Angular 6, I've tried to use async and await but cant really figure out how to get results and the error from the retrieveAllTeams

    You can do it in this way:

    async load() {
    
      // use try-catch block for handling errors
      try {
        // const result will have results from the 
        // retrieveAllTeams
        const result = await this.crmService.retrieveAllTeams();
    
        if (results.value !== undefined && results.value !== null) {
          var teams = results.value;
        }
      } catch (err) {
        // catch errors if any
        console.log(err);
      }
    }