![](/img/trans.png)
[英]How to watch variable in service from controller within AngularJS application?
[英]How do I set a variable within an Angular JS service to the response data from an $http call within an AngularJS service?
我有以下服务,我最终想要缓存。 但是,我似乎无法弄清楚如何在 Angular 中使用 $http 将服务中的变量设置为来自 REST 调用的响应数据。
routerApp.service('activityService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.temp = null;
this.setTemp(x) {
this.temp = x;
}
this.getActivities = function(x) {
var promise = $http({
method: 'GET',
url: 'my url is here...'
}).then(function(response) {
//setTemp(response.data); //definitely wont work
return response.data;
});
//how to set temp to response.data???
setTemp(promise.data); //doesn't work -
};
});
我不太了解 JS(或角度)。 做这个的最好方式是什么?
不需要缓存 angular 服务,它保证是一个单例。
如果您打算缓存响应数据,您将在您的服务中创建一个缓存对象。
现在关于主要问题。 在这段代码中,误用了承诺而不是角度服务。 Promise 是异步的,这意味着提供给.then()
的回调将在一段时间后执行,当请求完成时。 除了.then
返回另一个承诺,您应该从activityService.getActivities
方法返回。
this.getActivities = function(x) {
var promise = $http({
method: 'GET',
url: 'my url is here...'
}).then(function(response) {
setTemp(response.data); //meaning that setTemp somehow modifies it's argument
return response.data;
});
return promise;
};
然后在您的控制器之一中,您将使用此服务的方法将.then
附加到它的返回值。
.controller('someController', function (activityService) {
activityService.getActivities()
.then(function (data) {
doSomethingWithResponse(data);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.