如何创建一个角度库来拦截我的应用发出的HTTP请求

时间:2019-04-10 09:51:15

标签: angular npm angular-library

我正在尝试创建一个角度库,以拦截来自导入它的应用程序的http请求。 问题在于,如果拦截器是从库中导入的,则它不起作用,但是如果我将其移入我的应用程序中,它将起作用。

我库中的拦截器代码如下:

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

@Injectable()
export class SimpleInterceptor implements HttpInterceptor {
    constructor () {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            return throwError(err);
        }))
    }
}

我正在这样的应用程序(app.module.ts)中导入拦截器:

import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateCompiler, TranslateLoader, TranslateModule} from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { TranslateMessageFormatCompiler } from 'ngx-translate-messageformat-compiler';

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { SimpleInterceptor } from '@myname/angular-simple-library';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, 'languages/', '.json');
}

@NgModule({
  declarations: [],
  imports: [
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: createTranslateLoader,
          deps: [HttpClient]
      },
      compiler: {
          provide: TranslateCompiler,
          useClass: TranslateMessageFormatCompiler
      }
    })
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: SimpleInterceptor, multi: true },
  ]
})
export class AppModule {}

这里有什么问题的想法吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

当您在库中创建的拦截器是模块的一部分时,它应该可以工作。这意味着您需要在库项目中创建一个模块并将拦截器添加到其中。

例如npm软件包ngx-progressbar

import { NgModule, ModuleWithProviders } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgProgressInterceptor } from './ng-progress.interceptor';
import { NgProgressHttpConfig, NG_PROGRESS_HTTP_CONFIG } from './ng-progress-http.interface';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: NgProgressInterceptor, multi: true }
  ]
})
export class NgProgressHttpModule {
  static withConfig(config: NgProgressHttpConfig): ModuleWithProviders {
    return {
      ngModule: NgProgressHttpModule,
      providers: [
        { provide: NG_PROGRESS_HTTP_CONFIG, useValue: config }
      ]
    };
  }
}

如果添加拦截器,以后可以将库模块导入到应用模块中。

答案 1 :(得分:1)

我认为您在提供商中缺少括号,如下面的

providers: [
    [ { provide: HTTP_INTERCEPTORS, useClass: SimpleInterceptor, multi: true }, ]
  ]

如果上述方法无效,您可以查看如何在Angular HttpClient Guide上设置拦截器