我有一個角度應用程序,它有一個稱爲app的主模塊,然後是子模塊:app.ReportingApp,app.MediaJobApp,app.ManageUsers。Angular Service在聲明全局模塊時不被識別
我有一個服務,允許從本地存儲顯示一些警報,什麼不是。
我發現的問題是,當我將服務依賴項注入到控制器中時,我想從子模塊中使用它。然而,當我在我的服務中聲明'app.Reporting'而不是'app'時,它可以工作,但是在其他地方破壞了其他東西。
我不能使用這樣的服務嗎?從邏輯上講,在服務中調用主模塊並且子模塊能夠調用與主模塊相關的服務是有意義的,但看起來我可能不得不做另一種服務來滿足模塊之間的分離。
下面是一些代碼:
app.js:
angular.module('app', ['app.MediaJobApp', 'app.ManageUsers', 'app.ReportingApp'])
.run(function ($http) {
$http.defaults.headers.common['X-XSRF-Token'] =
document.getElementsByName('__RequestVerificationToken')[0].getAttribute("value");
});
app.ReportingApp.js:
angular.module('app.ReportingApp', []);
PageAlertService.js:
angular.module('app').service('PageAlertService', function() {
this.setAlert = function() {
console.log("In setAlert");
if (localStorage.getItem("Success")) {
var alertObj = {
alert: "Success",
alertMessage: localStorage.getItem("Success")
};
console.log(alertObj);
} else if (localStorage.getItem("Error") && localStorage.getItem("Error") != null) {
var alertObj = {
alert: "Error",
alertMessage: localStorage.getItem("Error")
};
};
return alertObj;
};
this.errorStatusCheck = function(error, successString) {
if (error.status = -1) {
localStorage.setItem("Success", successString);
} else {
localStorage.setItem("Error", "Error occured: " + error.status + error.statusText);
};
};
});
和頂部ReportingCtrl.js:
angular.module('app.ReportingApp').controller('ReportingCtrl',
[
'$scope',
'ReportingService',
'PageAlertService',
function ($scope, ReportingService, PageAlertService) {
我得到的錯誤是:Error: [$injector:unpr] Unknown provider: PageAlertServiceProvider <- PageAlertService <- ReportingCtrl
,我發現這是由於我上面提到的問題。
幫助將不勝感激!謝謝!
您的應用程序模塊依賴於app.ReportingApp模塊(反之亦然),因此您將無法訪問app.ReportingApp中的應用程序模塊中定義的服務。爲app.DataService等服務定義一個分離模塊,並將其作爲依賴項添加到您的應用中.ReportingApp模塊 – Knitesh
我創建了一個plnkr,我相信它演示了您的用例,並顯示它按預期工作。您可以查看devtools中的console.log。 https://plnkr.co/edit/IZyRm2srvysogQroESlL?p=preview – ChrisG
謝謝你們兩位,我現在明白了! – DDelgro