如何用HttpInterceptor拦截角度4的响应

时间:2017-09-12 05:13:59

标签: angular angular-http-interceptors

我有以下拦截器:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private tokenService: TokenService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.tokenService.getToken();

    if (token) {
      const authReq = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });

      return next.handle(authReq);
    }

    return next
      .handle(req)
//
      .getSomehowTheResponse()
      .andSaveTheTokenInStorage()
      .andPropagateNextTheResponse()
  }
}

我想从本地存储中的响应头中保存令牌,所有教程都显示如何拦截请求,但不是很清楚响应。

3 个答案:

答案 0 :(得分:13)

next.handle(req)返回一个observable,以便您可以订阅它:

return next.handle(req).map((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    // do stuff with response and headers you want
    event.headers
    event.body
  }
  return event;
})

要了解有关拦截器背后力学的更多信息,请阅读:

答案 1 :(得分:4)

您还需要导入库

    import 'rxjs/add/operator/map';

然后你使用如下。您还需要返回事件对象,以便可以在subscribe()函数中接收它。

    return next.handle(req).map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response and headers you want
      }
      return event; 
    });

答案 2 :(得分:0)

您可以尝试一下 1.为此:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from 
"@angular/common/http";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";

2。如果您使用的是紧凑型rxjs,则可以将“ tap”替换为“ do”

export class RoleInterceptor implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>>{
return next.handle(req).pipe(tap(
event=>{
console.log('Intercepted! response',event);
}
))    
}
}