Как я могу получить текущий язык от TranslateService для использования в HttpInterceptor - PullRequest
1 голос
/ 20 сентября 2019

Я заметил, что 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)
...