Matheus Lima
Matheus Lima

Reputation: 2143

AngularJS : Factories update variables

I need to update the variable notifications from my factory after the promise is resolved. The idea is to to call it like this:

InboxNotificationFactory.notifications

and this will return 0, and then when the promise is resolved it will update to some other value without the need to used .then() inside my controller.

inboxApp.factory('InboxNotificationFactory', function (inboxHttpService) {
    getNotifications();

    return {
        notifications: 0
    };

    function getNotifications() {
        inboxHttpService.totalUnreadMessages().then(function(response) {
            //ERROR RIGHT HERE
            this.notifications = response.data;
        });
    }
});

Upvotes: 0

Views: 28

Answers (1)

floatingLomas
floatingLomas

Reputation: 8747

this.notifications doesn't exist. Something like this is probably closer to what you want:

inboxApp.factory('InboxNotificationFactory', function (inboxHttpService) {
    var notifications = 0;

    inboxHttpService.totalUnreadMessages().then(function(response) {
        notifications = response.data;
    });

    return {
        notifications: notifications
    };
});

Upvotes: 1

Related Questions