Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use restangular with promise pattern in angular service

I have a service with rest angular with 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 access the countries from controller, the result is empty with a successful request with data, my question is how a can extract the data from response with proper promise pattern, ie( i need array of countries when i access scope.countries)

like image 884
Binson Eldhose Avatar asked Feb 13 '23 13:02

Binson Eldhose


1 Answers

You need to resolve promise...

There are two ways to do it...

1) Using $object

just add .$object to end of promise so once request is done it resolves promise...

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

2) Using then

if you need to do some stuff after promise is resolved pick this option, once request is done callback function in then will be fired

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
});
like image 155
Poyraz Yilmaz Avatar answered Mar 05 '23 16:03

Poyraz Yilmaz