问题:
如何从任何 Controller 调用 getPages
函数,将数据返回到 Controller 并将空的 Page.details.ref
对象替换为GET
响应数据?
无论哪个 Controller 调用该函数,这一切都可能在工厂内发生吗?
app.factory('Pages', function($http, ENV){
var Pages = {};
Pages.details =
{
pages:
{
length: 0,
offsets: []
},
ref:
{
//data goes here on success
},
getPages: function($scope) {
return $http.get(ENV.apiEndpoint + '/' + $scope.storeSlug + '/pages.json?code=' + $scope.promoCode)
.success(function(data){
// I want this Pages.details.ref to be replaced on success of getPages
Pages.details.ref = data;
$scope.handlePagesSuccess(data);
return data;
})
.error(function(data, status){
// console.log('error:' + status);
});
}
}
return Pages;
});
Controller : 该 Controller 调用初始化请求
app.controller('RandomCtrl', function($scope, Pages){
var handleSuccess = function (data) {
$scope.data = data;
}
Pages.details.getPages($scope).success(handleSuccess);
})
Controller #2: 该 Controller 仅使用请求的临时版本,与 RandomCtrl 之间没有任何关系。例如,此 Controller 通常是指令级 Controller ,其中父 ctrl 之间没有冒泡
app.controller('OtherCtrl', function($scope, Pages){
$scope.tempPage = Pages.details.ref;
})
从哪里调用 getPages 并不重要。我希望每次调用 getPages 时都替换 ref 。
最佳答案
看起来您正在尝试管理工厂内部的状态,这可能不是一个好主意。另外,在工厂中传递 $scope
也不是一个好主意。它们应该仅限于其自己的 Controller 。您可以改为缓存先前进行的调用的 Promise,并根据标志您可以返回缓存的 Promise 或进行实际的服务调用。
app.factory('Pages', function($http, ENV, $q){
var Pages = {};
var cachedPromise = {};
Pages.details =
{
pages:
{
length: 0,
offsets: []
},
getPages: function(request) {
//Get a request key to make sure you are returning right promise incase multiple product calls are made at the same time.
var reqKey = request.storeSlug + request.promoCode;
//if a call has already been made and there is a promise return it
if(cachedPromise[reqKey]) return cachedPromise[reqKey];
//Store the promise in the cache for lastCall retrieval
return cachedPromise[reqKey] = $http.get(ENV.apiEndpoint + '/' + request.storeSlug + '/pages.json?code=' + request.promoCode)
.then(function(result){
return result.data; //You can alter data and send as well
}, function(data, status){
return $q.reject('some error'); //or return some data
}).finally(function(){
//remove the cache from the map, once promise is resolved.
delete cachedPromise[reqKey];
});
}
}
return Pages;
});
在你的第一个 Controller 中执行以下操作:-
app.controller('RandomCtrl', function($scope, Pages){
//Build your request.
Pages.details.getPages(request).then(function (data) {
$scope.data = data;
});
});
在你的第二个 Controller 中执行相同的操作:-
app.controller('OtherCtrl', function($scope, Pages){
//Pass the flag to get the cached data.
Pages.details.getPages(request).then(function (data) {
$scope.tempPage = data;
});
});
关于javascript - 是否可以将 GET 响应数据传递回同一工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25373060/