简体   繁体   中英

Angular2 Router template request http headers

Simple question.

What does the Angular2 router use to make routing requests to the server? I need to insert custom headers (X-locale: 'en') on all template requests, so the server can translate them.

I have overridden BaseRequestOptions and the Http class and it is working on everything except the default routing calls. By that I mean the @Component template calls.


UPDATE #1

I will illustrate the issue

Here are the template requests that angular2 makes to my Laravel5 backend.

在此处输入图片说明

Notice the Main.Users.user Main.Users.user-detail

and so on.

These are all @Component template requests that Angular2 makes. I will also post the request details below

在此处输入图片说明

I need to insert the X-locale header into the http header of the @Component template requests. For that I need to know what class creates those requests, so I can somehow modify the request headers.


Update #2

I will also post my custom BaseRequestOptions code

class RequestOptionsWrapper extends BaseRequestOptions {
    constructor () {
        super();
        let locale = ( localStorage.getItem("locale") ) ? localStorage.getItem("locale") : "en" ;
        this.headers.append('X-locale', locale);
    }
}

//enableProdMode();
bootstrap(
    AppComponent,
    [
        ROUTER_PROVIDERS,
        ROUTER_DIRECTIVES,
        HTTP_PROVIDERS,

        provide(RequestOptions, { useClass: RequestOptionsWrapper })
    ]
)

This works as expected and is inserting X-locale into all the Http requests I make in the app, with the exception of the damn template calls, which are being excluded. I also overrode the Http class, but the @Component template calls are not calling neither the Http class, nor the BaseRequestOptions class.

Small example of a Http.post request

在此处输入图片说明

Thank you JB Nizet and Günter. I finally opted to using angular2-cookie instead of request headers.

I did a global CookieService service, which I provide for my app and which sets locale cookies, that are used in all template requests.

App.ts

import { CookieService }                                            from 'angular2-cookie/core';

//enableProdMode();
bootstrap(
    AppComponent,
[
    CookieService,

    ROUTER_PROVIDERS,
    ROUTER_DIRECTIVES,
    HTTP_PROVIDERS,

]
)  
.catch(err => console.error(err));

And the request

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM