vandango
vandango

Reputation: 567

Angular Components does not work with Promise and Service

I have a really strange problem with Angular Components calling a service. For example, i have a simple service with some mockup data as an array inside. The i add two methods, one synchron and one asynchron which returns a promise (if i correct understood). Now a have a angular component which is well loaded in a example application. On the frontend i have two buttons, one for each method in the service. If i press now the button "btn1" the list is well loaded, all works fine. If i now press the button "btn2" i see in the console that the service returns all data correctly, but the list in the frontend will not be loaded.

Service

var myItems = [
  {id: 1, name: "item1"},
  {id: 2, name: "item2"}
];

function ItemsService($q) { // inject the $q service
    this.$q = $q;
}

ItemsService.prototype = {
    loadItems: function () {
        return myItems;
    },

    loadItemsAsync: function () {
        var $qme = this.$q; // if i do not this, "this.$q" is undefined
        return this.$q.resolve(myItems);
    }
};

module.exports = {
    ItemsService: ItemsService
}

Controller

function Foo(ItemsService) {
    this.itemsService = ItemsService;
}

Foo.prototype = {
    loadItems: function () {
        this.items = this.itemsService.loadItems();
    },
    loadItemsAsync: function () {
        this.itemsService.loadItemsAsync().then(
            function (response) {
                this.items = response;
                console.log('data->' + this.items + ' -> ' + this.items[0].name);
            },
            function (error) {
                console.log('error->' + error); // ignore
            }
        );
    }
};

Component HTML

<section>
    <button id="btn1" ng-click="$ctrl.loadItems()">Load</button>
    <button id="btn2" ng-click="$ctrl.loadItemsAsync()">Load Async</button>
    <ul>
        <li ng-repeat="item in $ctrl.items">{{item.id}} // {{item.name}}</li>
    </ul>
</section>

In future i want to replace the code in the service method of "loadItemsAsync" with a service call, but actually nothing works.

Future planned service method code

loadTreasuriesAsync: function () {
    var $qme = this.$q;
    return this.$http.get(this.url).then(
        function (response) {
            return $qme.resolve(response.data);
        },
        function (error) {
            throw error;
        }
    );
}

I also tried this service call, but it also returns a promise object.

loadItems: function () {
    return this.$http.get(this.url).then(function (response) {
        return response.data;
    });
},

Can anyone help me finding a solution?

Upvotes: 0

Views: 662

Answers (1)

nuclearglow
nuclearglow

Reputation: 76

this.items = response;

this does not exist anymore in the context. Try to save the context previously either by an outside variable (i.e. _this) or use arrow functions if you have those available.

Upvotes: 1

Related Questions