2

The following approach does not work:

angular.module('myApp.myModule').factory('MyResource', function($resource, $cookies) {

    var token = $cookies.get('token');
    var user = $cookies.get('username');

    console.log ("Token: "+token+" User: "+user);

    return $resource(
        'http://my-rest-api/whatever/:id',
        {
            headers: {
            'token': token,
            'user': user
            }
        }
)});

Console shows the correct data, but they were not sent..

That's the part somewhere in the related Controller (excerpt):

var getEntryOne = MyResource.get({ id: 1 }, function() {
    console.log("Result: "+getEntryOne);
});

I get the "Message: Token invalid", I see the request-http-headers in firebug, they were not setted.

1 Answer 1

1

You are setting headers for get request then it should be there in get option of $resource

$resource('http://my-rest-api/whatever/:id',{},{
    get:{
        method:"GET",
        headers:{
            'token': token,
            'user': user
        } 
    },
});

If you wanted to add this header information to each request, then you could have http inteceptor which will be add header information on each request.

app.service('MyResourceInterceptor', ['$cookies', function($cookies) {
    var token = $cookies.get('token'),
        user = $cookies.get('username'),
        service = this;
    service.request = function(config) {
        config.headers['token'] = token;
        config.headers['user'] = user;
        return config;
    };
}]);

app.config([ '$httpProvider',   function($httpProvider) {
    $httpProvider.interceptors.push('MyResourceInterceptor');
}]);
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, I know that, but it should work for all methods. I don't want to write it each time at each method.
@Vienna then you should go for httpInterceptor & in that you could place this header on each request..
How can I use it in my case above?
@Vienna Glad to help you..Thanks :)
@TomSöderlund Injectors are singleton in AngularJS application, throughtout the application it same same injector instance. So that's why these interceptors are applicable all over $http call. If you want to specifically apply some changes to request/response just use transformRequest/ transformResponse based on your need
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.