Angular 5提供基于环境的HTTP拦截器

Ste*_*anN 5 javascript angular-http-interceptors angular

我的angular-cli(v1.5.1,angular v5)应用程序中具有以下两个环境:

  1. 开发者
  2. 产品

开发人员利用了模拟数据,该数据由http-interceptor提供。专业版使用实时休息API。

如何在dev上提供http-interceptor,在pro上不提供?我已经尝试了以下方法,但是不起作用:

{
  provide: HTTP_INTERCEPTORS,
  useFactory: () => {
    if (environment.useMockBackend === true) {
      return MockHttpInterceptor;
    }
    return false;
  },
  multi: true
}
Run Code Online (Sandbox Code Playgroud)

dhi*_*ilt 8

在我的 Angular 5.2 项目中,我使用了以下方法。

app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { environment } from '../environments/environment';
import { MyInterceptor } from './my.interceptor';

const commonProviders = [/*...*/];
const nonProductionProviders = [{ 
  provide: HTTP_INTERCEPTORS,
  useClass: MyInterceptor,
  multi: true
}];

@NgModule({
  imports: [
    HttpClientModule,
    // ...
  ],
  providers: [
    ...commonProviders,
    ...!environment.production ? nonProductionProviders : []
  ]
})
Run Code Online (Sandbox Code Playgroud)

my.interceptor.ts

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // ...
    return next.handle(req);
  }
}
Run Code Online (Sandbox Code Playgroud)


kem*_*sky 2

这个想法是从环境文件中导出拦截器提供程序,prod环境导出不执行任何操作的拦截器或任何其他虚拟提供程序(让我们命名它DefaultHttpInterceptor)和dev导出MockHttpInterceptor。

开发环境:export const INTERCEPTORS = {provide: HTTP_INTERCEPTORS, ... MockHttpInterceptor}

产品环境:export const INTERCEPTORS = {provide: HTTP_INTERCEPTORS, ... DefaultHttpInterceptor}

然后你就可以像平常一样使用它:

import { INTERCEPTORS } from './../environments/environment';
@NgModule({
providers      : [
        ...
        INTERCEPTORS 
        ...
    ]
...
})
Run Code Online (Sandbox Code Playgroud)