开发者问题收集

如何从 TranslateService 获取当前语言以在 HttpInterceptor 中使用

2019-09-20
3745

我注意到 Angular 不会将 Accept-Language 标头添加到请求中,我希望能够在后端检查语言。

我试图执行以下操作:

版本 1:

import { TranslateService } from '@ngx-translate/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(
        private translateService: TranslateService
    ) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.debug("Request intercepted by AuthInterceptor.");
        return next.handle(
            req.clone({
                headers: req.headers.append(
                    "Accept-Language", this.translateService.currentLang
                )
            })
        );      
    }
}

版本 2:

import { TranslateService } from '@ngx-translate/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable, Injector } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(
        private injector: Injector
    ) {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.debug("Request intercepted by AuthInterceptor.");
        return next.handle(
            req.clone({
                headers: req.headers.append(
                    "Accept-Language", this.injector.get(TranslateService).currentLang
                )
            })
        );        
    }
}

但这些都不起作用。我假设 TranslateService 不能在这里使用,就像在组件中一样。如果是这样,那么我如何获取所选语言并在拦截器中使用它?


更新: 使用版本 1,我收到以下错误:

ERROR TypeError: Cannot read property 'length' of undefined
    at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate (http.js:200)
    at http.js:171
    at Array.forEach (<anonymous>)
    at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init (http.js:171)
    at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach (http.js:236)
    at Observable._subscribe (http.js:1436)
    at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43)
    at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29)
    at subscribeTo.js:21
    at subscribeToResult (subscribeToResult.js:11)
2个回答

尝试使用版本 1,使用 ${this.translateService.currentLang 而不是 this.translateService.currentLang

Giant Ape
2020-06-10

对于 HttpInterceptor,您不能这样使用它。但是,在第一次安装时,您可以在存储中写入语言并再次调用它。类似下面的方法可能适合您。

在此处输入图片描述

Kenan
2022-12-08