Http拦截器无法在角度6中工作

时间:2018-09-18 10:52:12

标签: angular angular6

在我的angular 6项目中,我已经使用httpintercept来处理数据服务中的401(未经授权)错误。但是,httpintercept服务没有将其纳入我的项目。

这是我的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---");

          })
        )

    };


}

这是我的常用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())));
        }


    }

1 个答案:

答案 0 :(得分:7)

对于Angular 4.3及更高版本,您必须使用HttpClient而不是Http

拦截器与HttpClient一起使用,而不与Http一起使用。

因此,请改用以下导入:

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

在构造函数中:

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

有关this的更多信息,请参阅Http和HttpClient。