3

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

Pete Martin
  • 856
  • 7
  • 15
  • Which version of AngularJS are you using? According to http://stackoverflow.com/questions/12791667/how-to-specify-headers-parameter-for-custom-angular-resource-action setting request headers works since version 1.1.3. – pbetkier Oct 02 '13 at 21:29
  • @pbetkier I am using 1.1.3 - I want to know if it is possible to change the headers after creating the $resource. Thanks – Pete Martin Oct 02 '13 at 21:48

1 Answers1

4

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
    }
});
Community
  • 1
  • 1
Erstad.Stephen
  • 1,035
  • 7
  • 9
  • You could create the entire headers object with 'Authorization' as a property and assign the reference to that as the header property in current. You could then modify the object's properties which would give the updated values. – Erstad.Stephen Oct 02 '13 at 22:06