ChrisBratherton
ChrisBratherton

Reputation: 1590

AngularJS Data from a Service

So I have created a Notifications service in AngularJS and well I'm not getting any meaning full data back in my $scope.Notifications variable.

I can see the service is being called and running at the correct interval, and the correct data is being returned from the 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"}]

Essentially, all I need from this is a simple array of the users notifications.

Here is my service:

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()
    }
}];

And my controller:

app.controllers.notificationsController = ['$scope', 'Notifications', function($scope, Notifications) {
    $scope.Notifications = Notifications;
}];

If I console log $scope.Notifications in the controller I being return this:

Object {Notifications: d}Notifications: d$$state: Objectstatus: 1value: undefined__proto__: Object$$timeoutId: 1__proto__: Object__proto__: Object

Upvotes: 0

Views: 87

Answers (2)

br0tat0
br0tat0

Reputation: 539

Set your $scope.Notifications = Notifications.Notifications;

app.controllers.notificationsController = ['$scope', 'Notifications', function($scope, Notifications) {
    $scope.Notifications = Notifications.Notifications;
}];

Upvotes: 2

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Currently the thing which you are getting in console is nothing but a promise object which is conceptually correct. If you want the data from it then you use resolve that promise chain using .then function on Notification service.

Notifications.Notifications.then(function(data){
   $scope.Notifications = data;
}) 

Upvotes: 0

Related Questions