angular2 HttpClient中的拦截器不起作用?

发布于 2022-09-06 10:28:46 字数 1397 浏览 15 评论 0

1.我按照angular官方文档实现了httpclient发出http请求。文档链接
2.我尝试按文档在项目中实现拦截器,这是我的代码:

Universal.Interceptor.ts

import { Injectable, Inject,Injector, Optional } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/observable';
import { StorageService } from '../../shared/storage.service';
import { enable, destroy } from 'splash-screen';
import 'rxjs/add/operator/do';

@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
  private _StorageService: StorageService;
  constructor(private injector: Injector) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(req)
    return next.handle(req);

  }

}```

app.module.ts

...
**import { HTTP_INTERCEPTORS } from '@angular/common/http';**
**import { UniversalInterceptor } from './core/Interceptor/Universal.Interceptor';**

@NgModule({
  declarations: [
    AppComponent
  ],
...
  **providers: [{ provide: HTTP_INTERCEPTORS, useClass: UniversalInterceptor, multi: true }],**
  bootstrap: [AppComponent]
})

 }

项目的http请求还是正常的,但拦截器的console.log没有打印,项目也没有报错,是否引入少了内容?Universal.Interceptor.ts文件是我手动创建的,是否跟这个有关系?有没有使用这个拦截器的

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼藏柔 2022-09-13 10:28:46

你好,升级到4.3以后,新多出个HttpClient模块,如果要使用拦截器,需要,将老的http改为,HttpClient.
相关代码:

import { HttpClient } from '@angular/common/http';
this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(
  data => {
    console.log("User Login: " + data.login);
    console.log("Bio: " + data.bio);
    console.log("Company: " + data.company);
  },
  err => {
    console.log("Error occured.")
  }
);
苏佲洛 2022-09-13 10:28:46

我猜是你的拦截器并没有被使用。参考如下:

import { Injectable } from '@angular/core';
import { Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers, XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class CustomHttp extends Http {
 
  constructor(
      backend: ConnectionBackend,
      defaultOptions: RequestOptions
  ) {
      super(backend, defaultOptions);
  }
    request(url: string | Request, options ?: RequestOptionsArgs): Observable < Response > {
        return this.intercept(super.request(url, options));
    }

    get(url: string, options ?: RequestOptionsArgs): Observable < Response > {
        return this.intercept(super.get(url, options));
    }

    post(url: string, body: string, options ?: RequestOptionsArgs): Observable < Response > {
        return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable < Response > {
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
    }

    delete(url: string, options ?: RequestOptionsArgs): Observable < Response > {
        return this.intercept(super.put(url, this.getRequestOptionArgs(options)));
    }

    getRequestOptionArgs(options ?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers();
        }
        options.headers.append('Content-Type', 'application/json');
        return options;
    }

    // 拦截器
    intercept(observable: Observable < Response >): Observable < Response > {
         console.log('请求前');
        return Observable.create((observer) => {
          observable.subscribe(res => {
            observer.next(res);
          }, (err) => {
            observer.error(err);
          }, () => {
             console.log('complete');
             observer.complete(); 
          });
        });
    }

}

export let providerHttp = ( backend: XHRBackend,
        defaultOptions: RequestOptions
       ) => new CustomHttp(backend, defaultOptions);

然后在app.module.ts中

providers: [
         {
             provide: Http,
             useFactory: providerHttp,
             deps: [XHRBackend, RequestOptions, LoadingBarService]
         }
    ],
少年亿悲伤 2022-09-13 10:28:46

有可能是你的路由懒加载的问题,在路由加载的第一个组件是有作用的,你可以试一下

べ繥欢鉨o。 2022-09-13 10:28:46

这是我的拦截器:

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      headers: req.headers.set('X-CustomAuthHeader', 'AuthHeader')
    });
    console.log('request', clonedRequest);
    console.log("Observable", next.handle(clonedRequest));
    return next.handle(clonedRequest);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文