服务方法未返回承诺

时间:2020-02-04 17:17:12

标签: angular

在我的angular 8应用程序中,当发生异常时,promise调用不会返回异常。有人可以告诉我如何使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}`)

1 个答案:

答案 0 :(得分:0)

您应将ObservableHttpClientsubscribe方法一起使用。

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

您的get方法:

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

HttpClient的get方法返回一个Observable,并在出现任何问题时自动捕获错误。