Pete Martin
Pete Martin

Reputation: 856

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

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

Upvotes: 3

Views: 966

Answers (1)

Erstad.Stephen
Erstad.Stephen

Reputation: 1035

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
    }
});

Upvotes: 4

Related Questions