如何在角度服务中使用带有promise模式的restangular

Bin*_*ose 4 asp.net-web-api angularjs restangular

我有一个服务与休息角度与以下结构

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

    };
}
Run Code Online (Sandbox Code Playgroud)

也是一个控制器

function countryCtrl(scope, countrySvc) {


    scope.countries = countrySvc.countries();

}
Run Code Online (Sandbox Code Playgroud)

但是当我从控制器访问国家时,结果是空的,数据成功请求,我的问题是如何从具有正确承诺模式的响应中提取数据,即(当我访问scope.countries时我需要一组国家/地区)

Poy*_*maz 8

你需要解决承诺......

有两种方法可以做到......

1)使用 $object

只是添加.$object到承诺的结束所以一旦请求完成它解决了承诺...

scope.countries = countrySvc.countries().$object;
Run Code Online (Sandbox Code Playgroud)

2)使用 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
});
Run Code Online (Sandbox Code Playgroud)