Angular 4 - HTTP拦截器

时间:2017-06-06 18:05:22

标签: angular

我正在尝试在Angular 4中创建HTTP拦截器,但我有一些奇怪的错误。以下是我的错误:

Argument of type 'Observable<Response>' is not assignable to parameter of type 'Observable<Response>'.

以下是我的代码:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

@Injectable()
export class HttpInterceptor extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options)); // Here is the error
    }

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

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

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

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options)); // Here is the error
    }

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

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status == 401 && !_.endsWith(err.url, 'api/auth/login')) {
                this._router.navigate(['/login']);
                return Observable.empty();
            } else {
                return Observable.throw(err);
            }
        });

    }

}

有谁知道这里出了什么问题?我尝试了3个小时的调试,但无法找到任何线索。

修改

我也尝试删除所有内容并编写如下代码:

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
}

但它仍然给出同样的错误:

Argument of type 'string | Request' is not assignable to parameter of type 'string | Request'. Type 'Request' is not assignable to type 'string | Request'.

5 个答案:

答案 0 :(得分:43)

Http拦截器已在Angular 4.3.4中实现,并在documentation中进行了描述。

您需要实现intercept接口的HttpInterceptor方法,对请求执行某些操作,然后调用next.handle(req)方法。

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

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const changedReq = req.clone({headers: req.headers.set('My-Header', 'MyHeaderValue')});
    return next.handle(changedReq);
  }
}

在app的提供者部分注册拦截器也是必要的

import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: NoopInterceptor,
    multi: true,
  }],
})
export class AppModule {}

答案 1 :(得分:16)

akn的答案是对的。我试图使用 http 服务,但拦截器仅适用于 httpClient 服务。

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

constructor(private http: HttpClient) { }

答案 2 :(得分:4)

全局可用的DOM输入(tsconfig中的"lib": ["dom"])包括与Angular使用的类型无关的ResponseRequest接口。

您需要从Response导入Request@angular/http

答案 3 :(得分:2)

以下说明对我有用:

在app模块中:

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { myInterceptor} from './Interceptors/myInterceptor';

@NgModule({
    imports: [
...
    HttpClientModule,
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: MyInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent]
})

在拦截器中:

import { Injectable } from '@angular/core';

import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { HttpErrorResponse } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { HttpHeaders } from '@angular/common/http';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // when there is POST request
    if (req.method === 'POST') {
      const content_type = 'application/x-www-form-urlencoded';
      const req= req.clone({
        headers: req.headers.set('Content-Type', content_type),
        body: 'my body'
      });

      return next.handle(accessReq);
    }
  }
}

重要:http应该是HttpClient的一个实例!

constructor(
    private http: HttpClient, private accessTokenService: AccessTokenService
) { }
    return this.http.post(ingestURL, null)
        .map(res => {
            return res; // data returned from interceptor
        });

答案 4 :(得分:0)

使用此逻辑在任何框架中拦截Ajax。

private bootstrapAjaxInterceptor() {
const _self = this;
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (xhrMethod, requestUrl) {
  this.addEventListener('readystatechange', xhr => {
    switch (this.readyState) {
      case 1: _self.onAjaxStart(xhrMethod, requestUrl); break;
      case 4: _self.onAjaxStop(this.responseURL, this.response); break;
      default: // Nothing to handle here
    }
  }, false);
  originalOpen.apply(this, arguments);
};

}

以下是Angular的完整示例。

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
interface AjaxRequest {
  url?: string;
  requestCount?: number;
  method?: string;
}
interface AjaxResponse {
  url?: string;
  requestCount?: number;
  response?: string;
}
@Injectable()
export class HttpInterceptor {
  public ajaxStart = new BehaviorSubject<AjaxRequest>({});
  public ajaxStop = new BehaviorSubject<AjaxResponse>({});
  private requestQueue: Array<any> = [];
  constructor() {
    this.bootstrapAjaxInterceptor();
  }
  public getRequestQueue() {
    return this.requestQueue;
  }
  private bootstrapAjaxInterceptor() {
    const _self = this;
    const originalOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (xhrMethod, requestUrl) {
      this.addEventListener('readystatechange', xhr => {
        switch (this.readyState) {
          case 1: _self.onAjaxStart(xhrMethod, requestUrl); break;
          case 4: _self.onAjaxStop(this.responseURL, this.response); break;
          default: // Nothing to handle here
        }
      }, false);
      originalOpen.apply(this, arguments);
    };
  }
  onAjaxStart(xhrMethod, requestUrl) {
    this.requestQueue.push(requestUrl.replace(/\?.*/, ''));
    this.ajaxStart.next({
      url: requestUrl,
      requestCount: this.requestQueue.length,
      method: xhrMethod
    });
  }
  onAjaxStop(responseURL, response) {
    const responseUrl = responseURL.split(/\?/)[0];
    this.requestQueue.forEach((urlEndpoint, i) => {
      if (new RegExp(`${urlEndpoint}$`).test(responseUrl)) {
        return this.requestQueue.splice(i, 1);
      }
    });
    this.ajaxStop.next({
      url: responseUrl,
      requestCount: this.requestQueue.length,
      response: response
    });
  }
}