从异步请求(AngularJS)中获取对控制器中服务数据的引用



我很难理解控制器之间的数据共享。我想做的是(通过$http请求)从数据库中获取数据,将其存储在服务变量中,然后在不同的控制器之间共享。据我所知,这将允许我的视图在数据修改时自动更新。

简单地在服务内部声明变量并由控制器通过getter访问变量似乎很容易。但我试图共享的数据来自异步操作,我很难访问它

我想出了以下代码,我不明白为什么我一直得到一个"未定义"的变量。

文件:userController.js

function userController($scope, user)  //user = userService
{
user.getChallengeList(25)
.then(function(defiList)
{
$scope.allDefis = defiList;
console.log($scope.allDefis);  //ok
console.log(user.allDefis);  //undefined
});
}

文件:userService.js

function userService($http)
{
this.allDefis;
this.getChallengeList = function(id)
{
return $http
.post('http://localhost:3131/defi/defiList', {'id': id})
.then(function(response)
{
this.allDefis = response.data;
return this.allDefis;
});
}
}

从这段代码中,allDefis变量不应该在控制器内部访问吗?

没有在控制器中使用.然后"强制"它等待getChallengeList()方法的执行?

在这种情况下,为什么user.allDefis变量未定义?

我想我可以通过使用$rootscope来解决这个问题,但我宁愿不这样做,因为它似乎不是一个推荐的解决方案。

您的问题在于getChallengeList:的实现

this.getChallengeList = function(id)
{
return $http
.post('http://localhost:3131/defi/defiList', {'id': id})
.then(function(response)
{
this.allDefis = response.data; //<-- this is scoped here
console.log(this.allDefis);
return this.allDefis;
});
}

当您将web请求-响应数据分配给allDefis时,this的作用域是在匿名函数中,而不是整个函数中。

解决这一问题的一种技术是定义一个指向this的局部变量,并使用它。

你可以这样调整你的实现:

this.getChallengeList = function(id)
{
var _this = this; // a reference to "this"
return $http
.post('http://localhost:3131/defi/defiList', {'id': id})
.then(function(response)
{
_this.allDefis = response.data; // now references to correct scope
console.log(this.allDefis);
return this.allDefis;
});
}

最新更新