如何在bootstrap中为angular 4 app添加自定义拦截器

时间:2017-09-04 13:11:19

标签: angular angular4-httpclient

如何在bootstrap

中为angular 4 app添加自定义拦截器

我已经制作了一个基本的拦截器来最终设置一个身份验证令牌。

我需要帮助将拦截器添加到核心应用程序模块。

这是我的拦截器代码(目前非常基本):

import { NgModule } from "@angular/core";
import { routes } from "./app.routes";
import { BrowserModule } from "@angular/platform-browser";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { FormsModule} from "@angular/forms";
import { APP_BASE_HREF, CommonModule, } from "@angular/common";
import { RouterModule } from "@angular/router";
import { HttpModule, HTTP_INTERCEPTORS } from "@angular/http";

import { AppComponent } from "./app.component";
import { HomeModule } from "./components/home/home.module";
import { CommonInterceptor } from "./interceptor";

@NgModule({
  imports: [BrowserModule, FormsModule, RouterModule, CommonModule, HttpModule, RouterModule.forRoot(routes),
  HomeModule
  ],
  providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: CommonInterceptor,
        multi: true
    }
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

export class AppModule { }

这是我的应用模块(非常基本的应用):

*

我想将我的CommonInterceptor添加到app模块。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您无需将其添加到引导程序阵列即可使用它。

添加

{
        provide: HTTP_INTERCEPTORS,
        useClass: CustomHttp,
        multi: true
},

到您的提供者数组。

同样理想的拦截器看起来像,我无法理解你的版本:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import {Logger} from "../../logger/logger";
import 'rxjs/add/operator/do';

 @Injectable()
export class CommonInterceptor implements HttpInterceptor {

    className: string;
/**
 *
 * @param {Logger} logger
 */
constructor(private logger: Logger) {
    this.className = "CommonInterceptor";
}


/**
 *
 * @param {HttpRequest<any>} req
 * @param {HttpHandler} next
 * @returns {Observable<HttpEvent<any>>}
 */
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    return next.handle(req).do(event => {
        if (event.type == HttpEventType.Response) {
            if(this.logger.isDebugEnabled()){
                const elapsed = Date.now() - started;
                this.logger.debug(`${this.className}: Request for ${req.urlWithParams} took ${elapsed} ms.`);
            }
        }
    });

}
}

修改

添加了导入

答案 1 :(得分:0)

你app.module.ts中的

`

&#13;
&#13;
providers: [
     AccountService,
     AuthJwtService,
      AuthService,
     LocalStorageService,
     SessionStorageService,
     AuthGuardService,
//add this code bellow
     {
       provide: Http,
       useFactory: HttpIntercepter,
       deps: [XHRBackend, RequestOptions]
     }
   ]
&#13;
&#13;
&#13;

`

您可以在customhttp文件中添加简单的此函数

&#13;
&#13;
export function HttpIntercepter(backend: XHRBackend, options: RequestOptions) {
   return new CustomHttp(backend, options);
 } 
&#13;
&#13;
&#13;