javascript - Angular 5 提供基于环境的http拦截器

标签 javascript angular angular-http-interceptors

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

  1. 开发
  2. 产品

Dev 使用模拟数据,我提供了一个 http 拦截器。 Pro 使用实时休息 api。

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

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

最佳答案

在我的 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 : []
  ]
})

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

关于javascript - Angular 5 提供基于环境的http拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072426/

相关文章:

javascript - 这是javascript中的MVC吗?

javascript - 帮助文件和外部函数的 Jest 测试

javascript构造函数没有给出正确的结果

angular - 在安装 'sudo npm install -g @angular/cli ' 时,它在 ubuntu 中出现错误

Angular 4 - 拦截http请求并在登录后重新发送

angular - 如何仅为子模块注册 Angular HttpInterceptor

javascript - 使用 graphql 的 nestJS 中的解析器/服务有什么区别?

Angular 5 : Validating disabled fields

Angular 6 HTTP Interceptor 未设置 header

javascript - required set timeout 需要在 if else 条件下进行以下更改