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

角度HttpInterceptor修改错误对象

  •  0
  • naoru  · 技术社区  · 8 年前

    我已经实现了 HttpInterceptor 这会为每个请求添加一个标头,并在服务器响应时重定向到登录页面 401 . 我不想让它做任何其他事情。

    然而,我注意到,每当我从服务器得到错误响应时(正如我所期望的那样),拦截器就会踢它并抛出 HttpErrorResponse . 然而,在我的控制器中,我只得到一个 TypeError 对象,而不包含来自服务器的详细信息。

    我正在附上相关代码。

    拦截器

    @Injectable()
    export class HttpAuthorizationService implements HttpInterceptor {
    
      constructor(private cookieService: CookieService, private angularRouter: Router) { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler):  Observable<HttpEvent<any>> {
        req = req.clone({
          setHeaders: {
            Authorization: 'Bearer ' + this.cookieService.get('Authorization')
          }
        });
    
        return next.handle(req).do((ev: HttpEvent<any>) => {})
        .catch(error => {
          if (error instanceof HttpErrorResponse) {
            if (error.status === 401) {
              this.cookieService.set('expired', 'Session expired');
              this.angularRouter.navigate(['/login']);
            }
          }
          return Observable.throw(error); <-- i think this is bad
        });
      }
    }
    

    和实际 控制器

    deleteCategory(category) {
    this.confirmationService.confirm({
      message: 'Are you sure you want to delete?',
      header: 'Delete product category ' + category,
      icon: 'fa fa-trash',
      accept: () => {
        this.productService.deleteCategory(category).subscribe(
          success => {
            this.msgs = [{ severity: 'success', summary: 'Success', detail: 'Successfully deleted the product category ' + category }];
          },
          error => {
            this.categories.push(category);
            this.msgs = [{ severity: 'error', summary: 'Could not delete category', detail: error.status + '-' + error.error }]; <-- getting object without error attribute and no info from the server
          }
        );
      },
      reject: () => this.categories.push(category)
    });
    

    }

    我的问题是如何保留原始的错误对象,而不是我实际得到的 如果我没有实现这个HttpInterceptor,那么我的控制器就会得到正常的错误对象

    1 回复  |  直到 8 年前
        1
  •  0
  •   naoru    8 年前

    我不得不向HttpInterceptor实现添加另一个导入

    import 'rxjs/add/observable/throw';