【问题标题】:Angular interceptor is not adding custom param in requests角度拦截器未在请求中添加自定义参数
【发布时间】:2021-09-13 21:57:33
【问题描述】:

我使用 Angular 9,我想在所有发往后端的请求中添加国家/地区名称。

我找到了一篇博客,解释了如何使用拦截器添加请求参数

import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpEvent,
} from "@angular/common/http"
import { Observable } from "rxjs"

export class CountryInterceptorService implements HttpInterceptor {
    intercept(
        req: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const cloneReq = req.clone({
            params: req.params.set(
                "country",
                "France"
            ),
        })
        return next.handle(cloneReq)
    }
}

这是我的 app.modules

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NgxShimmerLoadingModule,
    SplashScreenModule,
    AlertModule.forRoot(),
    HttpClientModule,
    SimpleNotificationsModule.forRoot(),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    HighlightModule,
    LightboxModule,
    ClipboardModule,
    AppRoutingModule,
    InlineSVGModule.forRoot(),
    NgbModule,
  ],
  providers: [
    CookieService,
    {
      provide: HIGHLIGHT_OPTIONS,
      useValue: {
        coreLibraryLoader: () => import('highlight.js/lib/core'),
        languages: {
          xml: () => import('highlight.js/lib/languages/xml'),
          typescript: () => import('highlight.js/lib/languages/typescript'),
          scss: () => import('highlight.js/lib/languages/scss'),
          json: () => import('highlight.js/lib/languages/json')
        },
      },
    },
    IpInterceptorService,
    {
      provide : APP_INITIALIZER,
      useFactory : getIpService,
      deps: [IpInterceptorService, HttpClient],
      multi : true
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

export  function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
  return new TranslateHttpLoader(http);
}

/**
 * Call the service use to get the ip adress of the user, then the country
 * @param ipInterceptorService
 */
export function getIpService(ipInterceptorService : IpInterceptorService) {
  return ()=> ipInterceptorService.init();
}

但它不起作用。当我检查我的请求时,我的参数中没有国家。我错过了什么?

提前致谢。

【问题讨论】:

  • 看起来不错?你真的在 app.module 中提供了拦截器吗?
  • @MikeOne,不,我该怎么做?
  • 那就解释了:-)。有很多可用的例子,比如这个问题:stackoverflow.com/questions/51141132/…
  • @MikeOne 非常感谢。今天你是我的救星。
  • 不客气。享受编码!

标签: angular rxjs angular9 angular-http-interceptors


【解决方案1】:

您忘记以正确的方式提供拦截器。

在相应的模块中,您需要像这样提供它:

{provide: HTTP_INTERCEPTORS ,useClass: CountryInterceptorService, multi:true}

查看文档:https://angular.io/guide/http#provide-the-interceptor

【讨论】:

    猜你喜欢
    • 2016-02-02
    • 1970-01-01
    • 2023-03-19
    • 2019-09-19
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多