[英]AngularJS, service & promises
我在angularJS上工作了一段時間,我需要一些幫助。
這是我想做的:
我的問題:
我希望客戶能夠制作自己的彈出窗口,而不必關心服務如何調用應用程序。 我知道我可以使用控制器中的常規回調來完成此操作。但是由於它是在其中進行編碼的客戶端角色,因此我希望此部分盡可能簡單。
PS:當然,我之前測試了一個更簡單的實現,在控制器內部使用了回調等。它確實起作用。但是我需要保持如下所示的簡潔:
代碼示例:service:
angular.module("myService", []).service("MyService", ['$http', function($http){
this.propertiesInitialized = false;
this.availableLanguages = [];
this.availableResultTypes = [];
this.availableStates = [];
this.availableCrawlTypes = [];
this.dateFormat = "";
this.getProperties = function(callback)
{
$http.get("app/application-properties.json").success(function(JSONProperties) {
this.availableLanguages = JSONProperties.configurations.crawlerLanguages;
this.availableResultTypes = JSONProperties.configurations.resultTypes;
this.availableStates = JSONProperties.configurations.states;
this.availableCrawlTypes = JSONProperties.configurations.crawlTypes;
this.dateFormat = JSONProperties.configurations.dateFormat;
this.propertiesInitialized = true;
});
}
}]);
一個彈出窗口:
angular.module("popup1", ["MyService"])
.controller('Controller1', ['$scope', 'MyService',
function($scope, MyService) {
$scope.languages = MyService.availableLanguages;
$scope.crawlTypes = MyService.availableLanguagesCrawlTypes;
$scope.resultTypes = MyService.availableLanguagesResultTypes;
}]);
你有什么主意嗎?
謝謝 !
兌現諾言。
angular.module("myService", []).service("MyService", ['$http', '$q', function($http, $q){
var deffered = $q.defer();
var theService = this;
theService.propertiesInitialized = deffered.promise;
theService.availableLanguages = [];
theService.availableResultTypes = [];
theService.availableStates = [];
theService.availableCrawlTypes = [];
theService.dateFormat = "";
$http.get("app/application-properties.json").success(function(JSONProperties) {
theService.availableLanguages = JSONProperties.configurations.crawlerLanguages;
theService.availableResultTypes = JSONProperties.configurations.resultTypes;
theService.availableStates = JSONProperties.configurations.states;
theService.availableCrawlTypes = JSONProperties.configurations.crawlTypes;
theService.dateFormat = JSONProperties.configurations.dateFormat;
theService.propertiesInitialized.resolve();
});
}]);
angular.module("popup1")
.controller('Controller1', ['$scope', 'MyService',
function($scope, MyService) {
MyService.propertiesInitialized.then(function(){
$scope.languages = MyService.availableLanguages;
$scope.crawlTypes = MyService.availableLanguagesCrawlTypes;
$scope.resultTypes = MyService.availableLanguagesResultTypes;
});
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.