0

如何在引导程序中将自定义拦截器添加到 Angular 4 应用程序

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

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

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

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

@Injectable();

export class CommonInterceptor implements HttpInterceptor {
    className: string;

    constructor(private logger: Logger) {
        this.className = "CommonInterceptor";
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        return next.handle(req).do(event => {

          console.log("Interceptor");

            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.`);
                }
            }
        });

    }
};

这是我的应用程序模块(目前非常基本的应用程序):

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 添加到应用程序模块中。

我怎么做?

4

2 回答 2

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.`);
            }
        }
    });

}
}

编辑

添加了导入

于 2017-09-04T13:15:56.770 回答
0

在你的 app.module.ts `

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

`

您可以在您的 customhttp 文件中添加简单的此功能

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

于 2017-09-04T13:23:57.313 回答