3

In angular 1, I was able to manipulate the http object so the request header for a post included authentication like this:

$http.defaults.headers.common['Authorization'] = "Token " + sessionobject.token;

return $http({

    method: 'POST',
    url: SERVER_ENVIRONMENT + 'updatepath',
    headers: {
        'Content-Type': 'application/json',
        'Data-Type': 'json'
    },
    data: { 
        id : id,
        ...
    }
})

Can you please help me find the equvilant in Angular 2 that generates the same post request? many thnx in advance

Benjamin McFerren
  • 822
  • 5
  • 21
  • 36
  • already replied: http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request – thegio Apr 13 '16 at 06:52

2 Answers2

5

You extend the Angular2 class BaseRequestOptions to provide custom headers for all Http calls

class MyOptions extends BaseRequestOptions {
 header:Headers=new Header({
'Authorization': 'Bearer ' + localStorage.getItem('token')
 });
}

This class override can then be plugged into DI so that for the request options http picks MyOptions

bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})]);

The issue with this approach is that the token should be available during bootstrapping, which is not the case most of the time.

The other option is to create a custom http service. One such implementations is available here https://gist.github.com/chandermani/9166abe6e6608a31f471

Chandermani
  • 42,589
  • 12
  • 85
  • 88
2

As Chandermani said in his question you can specify your own options for requests. You can define things statically or a bit more dynamically by overriden the merge method. With the latter you can extend request options based of provided options for the current request.

For more details have a look at this question:

Since you use tokens, an important feature is that they expire after an amount of time. This means that you need to refresh them based on refresh tokens. This can be done transparently in Angular2 by extending the Http class and leveraging observable operators like flatMap.

For more details have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360