首页 > 解决方案 > 在服务中出现 Angular API 调用错误后向用户显示模板中的错误

问题描述

我将非常感谢一些帮助。当服务内部的 api 调用没有网络连接时,我试图在我的模板中向用户返回错误消息。

很多帮助已经过时了。

我的组件

this.dataService.GetQuotePopCats().subscribe(
    popCats => {
      this.popCats = popCats['data'];
    }, 
    error => {
        this.ErrMsg = "A PROBLEM"      <<< I want to display this in my template
        console.log("ERROR", error);   <<< NEVER GETS HERE
    }
);

在我的服务中...

GetQuotePopCats() : Observable<any> {
    const headers = new HttpHeaders({'No-Auth':'True'})
    headers.append('Content-Type', 'application/json')

    return this.http.get(this.globals.API_URL + 'GetQuotePopCats/?action=GETPOPCATS', {headers: headers}).pipe(
        map((res: any) => res.json()),
        catchError(<T>(error: any, result?: T) => {
            return of(result as T)
        })
    )
}

我已经复制了上面的代码,老实说我并没有完全理解它。

标签: angular

解决方案


因为您由of操作员处理错误

  catchError(<T>(error: any, result?: T) => {
            return of(result as T)
  })

在那种情况下总是会工作

popCats => {
      this.popCats = popCats['data'];
    }, 

您需要catchError从您的请求中删除或替换为

  catchError(<T>(error: any, result?: T) => {
            return throwError(result as T)
  })

推荐阅读