首页 > 解决方案 > 服务方法不返回承诺

问题描述

目前在我的 Angular 8 应用程序中,当发生异常时,promise call 不会返回异常。有人可以告诉我如何让 getRepApprovedName 返回一个承诺。如果我使用 return http.get,我会收到一个语法错误,提示需要大括号。

零件

 private getRepCode = (repCode: string) => {
    this.loading = true;
    const repToSend = fromGenistarCode(repCode);
    if (repToSend === 0) {
      this.splitSaleDetails.repName = '';
      return;
    }
    this.inviteService.getRepApprovedName(repToSend, this.currentUserId).then(rep => {
      if (rep) {
        this.splitSaleDetails.repName = rep.name;
      } else {
        this.splitSaleDetails.repName = '';
      }
      this.fieldDataChanged(new SetSplitSaleDetails(this.splitSaleDetails));
      this.loading = false;
    }).catch((err) => {
        console.log(err.message);
      return this.messageService.add(err.message, 'warning', true);
    });

服务

public getRepApprovedName = (repId: number, loggedInUserId: number): Promise<any> =>
      this.http.get(`${this.baseUrl}representative-name/${repId}/${loggedInUserId}`).toPromise()

建议的解决方案

  this.inviteService.getRepApprovedName(repToSend, this.currentUserId).subscribe(rep => {
      if (rep) {
        this.splitSaleDetails.repName = rep.name;
      } else {
        this.splitSaleDetails.repName = '';
      }
      this.fieldDataChanged(new SetSplitSaleDetails(this.splitSaleDetails));
      this.loading = false;
    },
    error => {
      this.messageService.add(error.message, 'warning', true);
   });






       public getRepApprovedName = (repId: number, loggedInUserId: number): Observable<any> =>
      this.http.get(`${this.baseUrl}representative-name/${repId}/${loggedInUserId}`)

标签: angular

解决方案


您应该使用ObservablewithHttpClientsubscribe方法。

this.inviteService.getRepApprovedName(...).subscribe(
  result => {
     // ok
  },
  error => {
     // catch error
  }
);

你的get方法:

getRepApprovedName(...): Observable<YourResultType> {
  return this.http.get<YourResultType>(...your url...);
}

HttpClientget 方法返回一个Observable并且会在出现任何问题时自动捕获错误。


推荐阅读