带有异步响应拦截器的 ngResource
ngResource with async response interceptor
我正在为使用 ngResource 的 API 调用编写响应拦截器,如下所示:
var Thing = $resource('/api/things/:id', {id: '@id'}, {
queryAll: {
method: 'GET',
interceptor: {
response: function(response) {
var instance = response.resource;
doAsyncStuffHere(instance.data);
return instance;
}
}
}
});
拦截器函数应该丰富响应中的数据,但 return 在异步操作完成之前是未修改的实例(正如预期的那样,因为它是异步的...)。
有没有什么好的方法,异步丰富数据,然后return语句"wait"直到完成?打回来?承诺?
使用示例:
https://docs.angularjs.org/api/ng/service/http#$http 参数;
属性"transformRequest"是更好的选择;
搜索正确的问题后,我找到了一篇文章解决了我的问题:
Sometimes there is a need to make some asynchronous operations inside the interceptor. Luckily AngularJS allows us to return a promise that will be resolved later. This will defer the request sending in case of request interceptor and will defer the response resolving in case of response interceptor.
发件人:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
这就是我的代码现在的样子,运行起来非常棒。
var Thing = $resource('/api/things/:id', {id: '@id'}, {
queryAll: {
method: 'GET',
interceptor: {
response: function(response) {
var instance = response.resource,
_deferred = $q.defer();
doAsyncStuffHere(instance.data).then(function() {
_deferred.resolve(instance);
});
return deferred.promise;
}
}
}
});
我正在为使用 ngResource 的 API 调用编写响应拦截器,如下所示:
var Thing = $resource('/api/things/:id', {id: '@id'}, {
queryAll: {
method: 'GET',
interceptor: {
response: function(response) {
var instance = response.resource;
doAsyncStuffHere(instance.data);
return instance;
}
}
}
});
拦截器函数应该丰富响应中的数据,但 return 在异步操作完成之前是未修改的实例(正如预期的那样,因为它是异步的...)。
有没有什么好的方法,异步丰富数据,然后return语句"wait"直到完成?打回来?承诺?
使用示例: https://docs.angularjs.org/api/ng/service/http#$http 参数;
属性"transformRequest"是更好的选择;
搜索正确的问题后,我找到了一篇文章解决了我的问题:
Sometimes there is a need to make some asynchronous operations inside the interceptor. Luckily AngularJS allows us to return a promise that will be resolved later. This will defer the request sending in case of request interceptor and will defer the response resolving in case of response interceptor.
发件人:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
这就是我的代码现在的样子,运行起来非常棒。
var Thing = $resource('/api/things/:id', {id: '@id'}, {
queryAll: {
method: 'GET',
interceptor: {
response: function(response) {
var instance = response.resource,
_deferred = $q.defer();
doAsyncStuffHere(instance.data).then(function() {
_deferred.resolve(instance);
});
return deferred.promise;
}
}
}
});