我想运行一项服务,当用户访问几个特定页面时,该服务会读取未读消息。我正在使用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'
});
}]);
})();
答案 0 :(得分:3)
问题是你在加载通知的函数中使用$ scope。 $ scope将无法在那里使用,因为它可能尚未创建。您需要返回一个promise,并且已解析的值可以作为依赖项注入控制器。
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
deferred.resolve(res.data.totalUnread);
});
return deferred.promise;
};
在您的控制器中,依赖于'通知'。
Ex: function HomeController($scope, $http, notifications){ }