所以我在AngularJS中创建了一个Notifications服务,而且我的$scope.Notifications
变量中没有任何含义的完整数据。
我可以看到正在调用服务并以正确的时间间隔运行,并且正在从API返回正确的数据:
[{"id":1,"user_id":1,"content":"You have new mail: Test","read":null,"type":"mail","deleted_at":null,"created_at":"2015-06-23 20:16:38","updated_at":"2015-06-23 20:16:38"},{"id":2,"user_id":1,"content":"You have new mail: Test","read":null,"type":"mail","deleted_at":null,"created_at":"2015-06-23 20:16:38","updated_at":"2015-06-23 20:16:38"},{"id":3,"user_id":1,"content":"You have new mail: Test","read":null,"type":"mail","deleted_at":null,"created_at":"2015-06-23 20:16:38","updated_at":"2015-06-23 20:16:38"}]
基本上,我需要的只是一个简单的用户通知数组。
这是我的服务:
app.services.Notifications = ['$http', '$timeout', function($http, $timeout){
var timeoutId;
var notificationService = this;
function checkForNotifications(){
console.log('checking')
return $http.get('/api/notifications')
.then(function(res){
return res.data.filter(function(notification){
return notification.unread === true;
})
})
.then(function(unreadNotifications){
//fake for effect
notificationService.count = Math.floor(Math.random() * (100 - 1)) + 1;
//notificationService.count = unreadNotifications.length;
})
.then(waitAndCheck)
}
function waitAndCheck(){
return $timeout(function(){
checkForNotifications()
},5000);
}
return {
Notifications: waitAndCheck()
}
}];
我的控制员:
app.controllers.notificationsController = ['$scope', 'Notifications', function($scope, Notifications) {
$scope.Notifications = Notifications;
}];
如果我在控制器中控制日志$ scope.Notifications,我将返回:
Object {Notifications: d}Notifications: d$$state: Objectstatus: 1value: undefined__proto__: Object$$timeoutId: 1__proto__: Object__proto__: Object
答案 0 :(得分:2)
设置$ scope.Notifications = Notifications.Notifications;
app.controllers.notificationsController = ['$scope', 'Notifications', function($scope, Notifications) {
$scope.Notifications = Notifications.Notifications;
}];
答案 1 :(得分:0)
目前你在控制台中获得的东西只不过是概念上正确的承诺对象。如果您需要来自它的数据,那么您可以使用.then
服务上的Notification
函数解析该承诺链。
Notifications.Notifications.then(function(data){
$scope.Notifications = data;
})