【发布时间】: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