Angularjs 如何在角度服务中使用Restanglar with promise模式
我有一个具有以下结构的服务Angularjs 如何在角度服务中使用Restanglar with promise模式,angularjs,asp.net-web-api,restangular,Angularjs,Asp.net Web Api,Restangular,我有一个具有以下结构的服务 function countrySvc(restangular) { restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) { if (operation === 'getList') { var newResponse = response.data; retu
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();
};
}
也是一个控制器
function countryCtrl(scope, countrySvc) {
scope.countries = countrySvc.countries();
}
但当我从controller访问国家时,如果成功请求数据,结果将为空,我的问题是a如何以适当的承诺模式从响应中提取数据,即(我访问scope.countries时需要一组国家)您需要解决承诺
scope.countries = countrySvc.countries().$object;
有两种方法可以做到这一点
1)使用$object
只需将$object
添加到承诺的末尾,这样一旦请求完成,它就会解析承诺
scope.countries = countrySvc.countries().$object;
2)使用然后
如果您需要在解决承诺后执行一些操作,请选择此选项,一旦请求完成,中的回调函数将被触发
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
});