![](/img/trans.png)
[英]How to use Angular.js service instance inside module config and keep the same instance
[英]How to use same service in two angular module
我試圖用谷歌搜索,但沒有得到我想要的答案。 我有兩個單獨的模塊(在單獨的html頁面中-這些模塊執行完全無關的任務)。 我已經創建了一個授權服務,並將其與模塊1關聯,並且正在通過DI在控制器中使用此$ auth服務。 現在,我想在module2中使用相同的服務。 我怎樣才能做到這一點? 這是服務的樣子:
module1.service('$authService', function($http) {
this.authorise = function(userid,accessKey) {
// logic for performing auth
};
});
您應該創建第三個通用模塊來托管您的authService
,並在其他兩個模塊中向該模塊添加依賴項。
angular.module("Auth", [])
.service("authService", function($http){ });
並且,在另一個文件/模塊/應用中:
angular.module("module1", ["Auth"])
.controller("MainCtrl", function(authService){
});
(與第二個模塊相同: angular.module("module2", ["Auth"])
)
在創建第二個模塊時,說module2提供了module1的依賴關系,就像
angular.module('module2',['module1']);
現在,您可以像在module1中一樣使用module1的服務到module2中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.