[英]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) 但是当我从控制器访问国家时,结果是空的,并且数据成功请求,我的问题是如何从具有正确承诺模式的响应中提取数据,即(当我访问scope.countries时我需要一组国家/地区)
You need to resolve promise... 你需要解决承诺......
There are two ways to do it... 有两种方法可以做到......
1) Using $object
1)使用
$object
just add .$object
to end of promise so once request is done it resolves promise... 只需添加
.$object
即可结束承诺,一旦请求完成,它就会解除承诺......
scope.countries = countrySvc.countries().$object;
2) Using then
2)
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 如果你需要在承诺解决后需要做一些东西选择这个选项,一旦请求完成回调函数
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.