如何创建一个 Angular 库来拦截我的应用程序发出的 http 请求

And*_*rei 6 npm angular 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);
        }))
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的应用程序中导入拦截器,如下所示(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 {}
Run Code Online (Sandbox Code Playgroud)

关于这里可能出什么问题的任何想法吗?谢谢你!

adi*_*ii4 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 }
      ]
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

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