vincentsty vincentsty - 2 months ago 21
AngularJS Question

Refactoring angular resource chaining

Basically i have a angular resource API service as follow. I have use the nested chaining method as below which i think is not so good in coding perspective (especially when there are multiple chaining needed)

angular.module('user')
.factory('UserAPI', ['$resource'],
function ($resource) {
return $resource('User', {},
{
GetUserDetail1: {
method: 'GET',
url: url1
},
GetUserDetail2: {
method: 'GET',
url: url2
}
}
}
)

UserAPI.GetUserDetail1({ ID: id }).$promise.then(function (res) {
UserAPI.GetUserDetail2({ ID: res.userID }).$promise.then(function (res1) {

}, function (errRes1) {

});
}, function (errRes) {

});


So, I am now thinking of refactoring the code as follow but I am not sure whether this could be done.

function getUserDetail2 (res) {

};

UserAPI.GetUserDetails1({ ID: id})
.then(getUserDetail2(res))
.catch(function (errRes) {
// catch error if any error occur
});

Answer

You just need to pass reference of function instead of calling it there.

UserAPI.GetUserDetails1({ ID: id})
.then(getUserDetail2) //passed getUserDetail2 method here
.catch(function (errRes) {
    // catch error if any error occur
});