代码之家  ›  专栏  ›  技术社区  ›  user68288

如何使用管道和映射将catchError添加到角度http调用?

  •  1
  • user68288  · 技术社区  · 4 年前

    尝试构建一些简单的功能,这样我就可以知道API调用何时返回401的错误代码(这样我就可以由于令牌过期而返回登录页面)。

    我试图通过捕捉通话中的错误,然后将用户注销来实现这一点。

    目前我的API服务工作得很好,但我找不到正确实现catchError的方法。

    工作电话

      getViT(x): Observable<CursorResult[]> {
        const url = hosturl +'vit';
            const httpOptions = {
            headers: new HttpHeaders({
              'Access-Control-Allow-Origin':  '*',
              'Content-Type': 'application/json',
              'Authorization': ls
            }),
            withCredentials: true,
            params: {
            }
          };
        return this._http.get(url, httpOptions)
        .pipe(
          map((res) => {
            console.log(res);
            return <CursorResult[]> res;
          })
        );
      }

    尝试添加catchError

      getViT(x): Observable<CursorResult[]> {
        const url = hosturl +'vit';
            const httpOptions = {
            headers: new HttpHeaders({
              'Access-Control-Allow-Origin':  '*',
              'Content-Type': 'application/json',
              'Authorization': ls
            }),
            withCredentials: true,
            params: {
            }
          };
        return this._http.get(url, httpOptions)
        .pipe(
          map(res => {
            return <CursorResult[]> res;
           }),
          catchError((err, caught) => {
            console.log('err ' + err)
            return err;
          })
       )
      }

    Visual studio告诉我以下内容:

    Type 'Observable<unknown>' is not assignable to type 'Observable<CursorResult[]>'.
      Type '{}' is missing the following properties from type 'CursorResult[]': length, pop, push, concat, and 28 more.ts(2322
    

    任何想法都将不胜感激。谢谢

    编辑

    我能够让下面的代码正常工作,但任何时候出现错误,它都会一次又一次地攻击API,直到我杀死docker容器。这是因为地图吗?

    getViT(x): Observable<CursorResult[]> {
      const url = hosturl +'vit';
          const httpOptions = {
          headers: new HttpHeaders({
            'Access-Control-Allow-Origin':  '*',
            'Content-Type': 'application/json',
            'Authorization': ls
          }),
          withCredentials: true,
          params: {
          }
        };
        return this._http.get<CursorResult[]>(url, httpOptions)
        .pipe(
            map((res) => {
              return <CursorResult[]> res;
            }),
            catchError((err, caught) => {
              console.log('API Error: ' + JSON.stringify(err));
              return caught
            }),
          )     
    }
    0 回复  |  直到 4 年前
        1
  •  1
  •   szymonhel    4 年前

    Http拦截器解决方案:

    @Injectable()
    export class UnauthorizedInterceptor implements HttpInterceptor {
    
      constructor(private router: Router) {
      }
    
      intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        {
          return next.handle(request)
            .pipe(
              catchError((error: HttpErrorResponse) => {
                if (error.status === 401) {
                  const _ = this.router.navigate(['login']);
                }
                return throwError(error);
              })
            );
        }
      }
    

    然后将其定义为模块中的提供者

    @NgModule({
      declarations: [],
      imports: [],
      exports: [],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: UnauthorizedInterceptor,
          multi: true,
        }
      ]
    })
    
    推荐文章