Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the header config of an AngularJS $resource object?

Tags:

rest

angularjs

Here's my code:

var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '@_id'} ,{
    login: {
        method: 'POST',
        params: {
            id: 'login'
        },
        transformResponse: function(data) {
            data = angular.fromJson(data);
            userAuth = 'Kinvey '+data._kmd.authtoken;
            return data;
        }
    },
    current: {
        method: 'GET',
        params: {
            id: '_me'
        },
        headers: {
            'Authorization': userAuth
        }
    }
});

I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?

EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks

like image 634
Pete Martin Avatar asked Dec 29 '25 01:12

Pete Martin


1 Answers

Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.

AngularJS resource not setting Content-Type

EDIT:

See my comment below for the explaination of this code.

var customerHeaders = {
    'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '@_id'} ,{
    login: {
        method: 'POST',
        params: {
            id: 'login'
        },
        transformResponse: function(data) {
            data = angular.fromJson(data);
            customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
            return data;
        }
    },
    current: {
        method: 'GET',
        params: {
            id: '_me'
        },
        headers: customHeaders
    }
});
like image 52
Erstad.Stephen Avatar answered Dec 30 '25 17:12

Erstad.Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!