【问题标题】:Return value of promise from service to component从服务到组件的承诺返回值
【发布时间】:2019-07-12 20:07:42
【问题描述】:

我有一个服务类如下

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

}

我在组件中这样调用它:

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

        });
}

所以retrieveAllTeams 返回一个RetrieveMultipleResponse 类型的Promise。界面是这样的:

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

我想避免在我的组件中使用嵌套的 Promise,所以我使用的是 Angular 6。我尝试使用 asyncawait,但我真的不知道如何获得结果和错误我的组件中的 retrieveAllTeams 方法。

【问题讨论】:

    标签: angular async-await es6-promise


    【解决方案1】:

    我想避免在我的组件中使用嵌套的 Promise,所以我使用的是 Angular 6,我尝试使用 async 和 await,但无法真正弄清楚如何从 retrieveAllTeams 中获取结果和错误

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2016-03-12
      相关资源
      最近更新 更多