For example, I have a controller to show user a list view, some columns need data comes from another endpoint, so I wrote these with intuition, could you tell me how do I re-factory them?
$http.get($scope.urlA)
.success(function(res){
$scope.dataA = res.data;
$http.get($scope.urlB)
.success(function(res){
$scope.dataB = res.data;
})
.error(function(err){
if (err) throw err;
});
})
.error(function(err){
if (err) throw err;
});
Then best practice would be two create two factory methods for the two $http.get calls. In Angular $http invoke promises by itself so your factory will look like:
myapp.factory('getHttpData',function($http){
return{
getURLA:function(){
return $http.get('/urlA');
},
getURLA:function(){
return $http.post('/urlB');
}
}
});
Then in Controller you can invoke both the factory functions like this:
.controller('testCtrl',['getHttpData',function(getHttpData){
getHttpData.getURLA().then(function(data){
//do whatever you want
getHttpData.getURLB().then(function(Bdata){
//do whatever you desire
}):
});
});
It doesn't look like the second call depends on the first so you can just call them separately:
$scope.data = {};
$http.get('http://example/url/a')
.success(function(data) {
$scope.data.a = data;
});
$http.get('http://example/url/b')
.success(funciton(data)) {
$scope.data.b = data;
});
If call b depends on data from call a then call service b from call a's success callback.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.