简体   繁体   English

Http Interceptor无法工作在角度6

[英]Http Interceptor not working in angular 6

I have used httpintercept for handling 401 (Unauthorized) error in data services in in my angular 6 project.But httpintercept service not taking in my project. 我已经使用httpintercept处理我的角度6项目中的数据服务中的401(未授权)错误。但httpintercept服务不接受我的项目。

This is my intercept.services.ts file 这是我的intercept.services.ts文件

export class InterceptService  implements HttpInterceptor {

  constructor(private authService: AuthService) { }

  // intercept request and add token
    intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

      // modify request
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${JSON.parse(localStorage.getItem('currentUser')).token}`
        }
      });

       console.log("----request----");

     console.log(request);

     console.log("--- end of request---");


      return next.handle(request)
      .pipe(
          tap(event => {
            if (event instanceof HttpResponse) {

              console.log(" all looks good");
              // http response status code
              console.log(event.status);
            }
          }, error => {
           // http response status code
              console.log("----response----");
              console.error("status code:");
              console.error(error.status);
              console.error(error.message);
              console.log("--- end of response---");

          })
        )

    };


}

This is my common service.ts page 这是我常见的service.ts页面

 import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    import {Http, Response,Headers ,RequestOptions } from "@angular/http";
    import { HttpModule} from '@angular/http';
    import { map } from 'rxjs/operators';
    import { Router } from '@angular/router';

     const API_URL   =  '//api path';



    @Injectable({
        providedIn: 'root'
    })
    export class DataService {
        ctrURL:any;
        postData:any;
        ajaxdata:any;

        constructor(private http:Http,private router: Router) { }
        get_data(url,auth=true){
            //......url : url path......
            //....auth : true api auth required,false no api required....
            var get_url = API_URL + url;
            var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            headers.append('Accept', 'application/json');
            if(auth==true){
                var localStore =    JSON.parse(localStorage.getItem('currentUser'));
                headers.append("Authorization", "Bearer " + localStore.token);
            }
            let options = new RequestOptions({ headers });
            return this.http.get(get_url, options) .pipe((map(res => res.json())));
        }


    }

For Angular 4.3+ and above you must use HttpClient instead of Http . 对于Angular 4.3+及更高版本,您必须使用HttpClient而不是Http

Interceptors work with HttpClient and not Http . 拦截器使用HttpClient而不是Http

So use below import instead: 因此请使用以下导入:

import { HttpClient, HttpHeaders } from '@angular/common/http';

And in constructor: 在构造函数中:

constructor(private http:HttpClient,private router: Router) { }

Refer this answer for more on Http and HttpClient. 有关Http和HttpClient的更多信息,请参阅答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM