One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following:
var token = $.get('/some-url', {}, someCallback);
token.oSomeObject = {data: 'some data'};
function someCallback( data, status, token ){
token.oSomeObject.data // 'some data'
}
I utilize the token to store request-specific data.
In Angular, the only way I have found to achieve this is by storing the data in the actual config object:
var config = {
url: '/some-url',
method: 'GET',
oSomeObject: { data: 'some data' }
};
$http(config).success(someCallback);
function someCallback( data, status, headers, config ){
config.oSomeObject.data // 'some data'
}
This approach not only hinders the use of shorthand calls ($http.get, $http.post) but also seems more cumbersome when encapsulating the calls in a specific service module.
Is there an alternative method to address this issue?
Additional Clarification
It's possible that I am overlooking a simple solution regarding how to properly utilize the promise API. To ensure clarity, allow me to provide more context on the matter.
I have two files: 1) Controller.js and 2) AjaxServices.js (where all ajax calls are defined as methods on a service).
The content of AjaxServices.js is as follows:
app.service('AjaxService', function( $http ){
var self = this;
this.createUser = function( oUser, fSuccessCallback ){
return $http.put('/api/user', {oUser: oUser})
.success(fSuccessCallback);
}
}
As for Controller.js, it appears like this:
app.controller('MyController', function( $scope, AjaxServices ){
$scope.saveUser = function( oUser ){
var oPromise = AjaxServices.createUser( oUser, $scope.onUserSaved );
oPromise.oUser = oUser // This is my workaround from using jQuery.ajax.
// The oPromise will be passed as the token object in the onUserSaved callback
}
$scope.onUserSaved = function( oStatus, status, headers, config ){
oStatus.id // Here lies the id of the newly created user,
// which I aim to link with the local oUser object now
}
}
How would you handle the same scenario utilizing the promise API?