本文介绍了如何创建一个角度库来拦截我的应用发出的HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create an angular library that intercepts http requests from the app it is imported in.The issue is that the interceptor doesn't work if it is imported from the library but if I move it inside my app it is working.

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

the interceptor code from my library looks like this:

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)中导入拦截器:

I'm importing the interceptor in my app like this (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 {}

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

Any ideas of what could go wrong here?Thank you!

推荐答案

我认为您缺少提供商中的括号,例如

I think you are missing a bracket in your providers, like below

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

如果上述方法不起作用,您可以查看如何在

If the above does not work, you can review how to setup an interceptor in the Angular HttpClient Guide

这篇关于如何创建一个角度库来拦截我的应用发出的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 09:09