[英]Sending data to factory from controller?
我的工厂是:
myAppServices.factory('ProfileData',['$http', function($http){
return{
newly_joined:function(callback){
$http.get(
//myUrl will be an url from controller.
myUrl
).success(callback);
}
};
}
]);
我有三个具有不同URL的控制器:
控制器1:
AppControllers.controller('ProfileListCtrl',['$scope','$state', '$rootScope', 'ProfileData', '$timeout', function($scope, $state, $rootScope, ProfileData, $timeout ) {
ProfileData.newly_joined(function(response) {
var myUrl= "www.abc...."
//something goes there
});
}]);
控制器2:
AppControllers.controller('ProfileListCtrl1',['$scope','$state', '$rootScope', 'ProfileData', '$timeout', function($scope, $state, $rootScope, ProfileData, $timeout ) {
ProfileData.newly_joined(function(response) {
var myUrl= "www.abc...."
//something goes there
});
}]);
控制器3为:
AppControllers.controller('ProfileListCtrl2',['$scope','$state', '$rootScope', 'ProfileData', '$timeout', function($scope, $state, $rootScope, ProfileData, $timeout ) {
ProfileData.newly_joined(function(response) {
var myUrl= "www.abc...."
//something goes there
});
}]);
由于URL不同,我想在不同的控制器中使用不同的数据,并且我在单个网页上显示所有三个详细信息。
因此,如果在工厂中有任何发送“ myUrl”的方法,我可以使用它来提取数据。
注意:请不要建议我使用$ resource或$ routeparams,因为$ resource无法成功从json提取数据,并且我不想在页面上使用大变量Url。
提前致谢
您需要做的就是向new_joined函数添加一个附加参数:
newly_joined:function(callback, myUrl){
另外,您应该使用.then而不是.success
您的工厂应该返回承诺而不是使用回调。
myAppServices.factory('ProfileData',['$http', function($http){
return function(myUrl) {
return $http.get(myUrl);
};
}]);
控制器
AppControllers.controller('ProfileListCtrl',['$scope', 'ProfileData', function($scope,ProfileData) {
var myUrl= "www.abc....";
var httpPromise = ProfileData(myUrl);
httpPromise.then(function onFulfilled(response) {
$scope.data = response.data;
}).catch(function onRejected(response) {
console.log("ERROR ", response.status);
});
}]);
使用promise的优点是它们保留错误信息。
还要注意, myUrl
作为参数发送到工厂。
有关使用promise优点的更多信息,请参见为什么从Promise然后方法进行回调是一种反模式?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.