How to use restatular template with promises in angular service

I have an angular rest service with the following structure

function countrySvc(restangular) {
    restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) {

        if (operation === 'getList') {
            var newResponse = response.data;

            return newResponse;
        }
        return response;
    });
    var baseCountry = restangular.all('country');


    this.countries = function() {

        baseCountry.getList();

    };
}

also a controller

function countryCtrl(scope, countrySvc) {


    scope.countries = countrySvc.countries();

}

but when I get access to countries from the controller, the result is empty with a successful data request, my question is how can I extract data from the answer with the correct promise template, i.e. (I need an array of countries when I access the .countries area)

+4
source share
1 answer

You need to resolve the promise ...

There are two ways to do this ...

1) Using $object

just add .$objectpromises to the end, so as soon as the request is completed, it promises ...

scope.countries = countrySvc.countries().$object;

2) Using then

, , , , then

scope.countries = countrySvc.countries().then(function (response){
    // DO SOMETHING IF YOU NEED BEFORE SET OBJECT
    scope.countries = response;
    // DO SOMETHING IF YOU NEED AFTER SET OBJECT
});
+8

Source: https://habr.com/ru/post/1547725/


All Articles