我使用工廠在用戶登錄後獲取JSON數據。如果用戶名和密碼正確,它應該從api鏈接中提取JSON數據。我的應用程序中有幾個控制器需要使用這些數據。我想避免與我的所有控制器共享這個工廠,因爲我不想保留「獲取」數據。我只希望這個工廠和登錄控制器一起使用。保存其他控制器使用的'GET'請求的數據?
如何從'dummyData'保存數據,然後所有其他控制器都可以使用該數據,而不必每次都發出'GET'請求?
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.saveData = function(user,password) {
var deferred = $q.defer();
var req = $http({
method: 'GET',
url: 'http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/login/login/?username='+user+'&password='+password
});
req.success(function(response) {
deferred.resolve(response);
});
req.error(function(err) {
console.log("there was an error: "+err);
deferred.reject(err);
});
return deferred.promise;
}
return apiServices;
}]);
您可以使用[$ cacheFactory](https://docs.angularjs.org/api/ng/service/$cacheFactory)並在第一次調用後保存結果 –
看看我在這篇文章中的回答: http://stackoverflow.com/questions/33968655/how-can-i-use-my-json-without-triggering-a-new-api-request-everytime-i-want-to-u/33969521#33969521 – sjokkogutten
你可以使用['$ rootScope'](http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html)嗎?一個例子[SO帖子](http://stackoverflow.com/questions/21444100/angularjs-how-to-http-get-data-and-store-it-in-service) –