在httpInterceptor中过滤请求 - Angular 4.3+

时间:2017-10-19 01:55:29

标签: angular angular4-httpclient

我有一个身份验证拦截器,但是,我想让这个拦截器过滤请求,而不是在用户访问不需要用户身份验证的确认帐户密码等组件时应用。关于如何去做的任何例子?这是auth拦截器的逻辑:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;

    //For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times.
    //So Clone the request before adding the new header. 
    //NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests.
    const authReq = request.clone({
      setHeaders: {
        Authorization: authHeader,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    });
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
}

1 个答案:

答案 0 :(得分:1)

对于这种情况,您的请求的网址很有帮助。

假设您的身份验证网址与auth/login or auth/refreshToken类似,而您的资源配置文件如api/users, api/users/123, api/addUser,那么您可以设置if条件来检查请求的用途。

网址匹配示例: -

 if (request.url.match(/api\//)) { // api call
    console.log('api call detected.');
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;
    const authReq = request.clone({
    setHeaders: {
       Authorization: authHeader,
       'Cache-Control': 'no-cache',
       'Pragma': 'no-cache'
     }
    });
    return next.handle(authReq);
 }
 else{ // auth call - you can put esle if conditions if you have more such pattern
 console.log('auth call detected.');
    return next.handle(request);
 }     

现在authentication headers只会添加到您的api-call(我的意思是资源api-call),其他调用不会被修改。

  

注意:我已经使用Java,DB等后端技术了更长时间   时间和现在第一次学习角度,所以回答像一个   mod:P,但这个想法来自我上一个Java项目。希望能帮助到你..!!   :)