我想運行一個服務,當用戶訪問幾個特定頁面時,該服務會讀取總未讀消息。我爲此使用了resolve
。我建立了一個通過http調用與後端進行通信的工廠,後端返回了總消息的數量,我想在html頁面中顯示,但是我得到的所有錯誤都是錯誤的。
(function() {
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
console.log('this is me');
$scope.numOfNotifications =res.data.totalUnread;
});
}
angular.module('myApp', [
'ngRoute',
'myApp.login',
'myApp.home',
'myApp.directory',
'myApp.forgotpassword',
'myApp.myProfile',
])
.factory('AuthService3', ["$http", "$location", function($http, $location){
var baseUrl = 'api/';
var fetchUnreadNotifications = function()
{
return $http.post(baseUrl + 'getAllUnreadNotifications');
}
return {fetchUnreadNotifications: fetchUnreadNotifications} ;
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/components/login/loginView.html',
controllerAs: 'vm'
})
.when('/forgotpassword', {
controller: 'ForgotpasswordController',
templateUrl: 'app/components/forgotpassword/forgotpasswordView.html',
controllerAs: 'vm'
})
.when('/directory/:directoryType', {
controller: 'DirectoryController',
templateUrl: 'app/components/directory/directoryView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'app/components/home/homeView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/myprofile', {
controller: 'MyProfileController',
templateUrl: 'app/components/profile/myProfileView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
}]);
})();
控制器在哪裏? – Subash
控制器都在那裏。這是路由發生的地方的文件,我使用resolve從這裏發送一個http調用。因此,儘管每個頁面都有控制器,但這裏不需要控制器。爲了減少歧義,我沒有包含它們。 @Subash – Annabelle
'$ scope'在resolve方法裏面不會有效,它應該只返回promise的一個期望的結果 –