努力理解 http 请求和 promise 的概念。我知道 http 请求是异步的,但不知道如何实现 promise 并返回数据以更新 $scope 变量,以便可以在任何地方访问。
此刻 $scope 变量只在 '.then' 中打印出来
基本上我试图将“season_number”返回到一个数组中,因此它显示为:
Array[
{season_number: 1},
{season_number: 2},
{season_number: 3},
{season_number: 4},
{season_number: 5}
];
代码:
$scope.seasonDetails = [];
var getSeasons = function() {
var data = "";
$http({
method: 'GET',
url: url
})
.then(function(response) {
var tvSeasonDetails = [];
for (var i = 0; i < response.data.seasons.length; i++) {
tvSeasonDetails.push(response.data.seasons[i].season_number)
}
$scope.seasonDetails = tvSeasonDetails;
console.log($scope.seasonDetails); //<----Variable displayed here
})
}
getSeasons();
console.log($scope.seasonDetails); //<---- Empty Array displayed here
最佳答案
正如您所指出的,$http.get()
是异步的。因此,当您调用 getSeasons 时,它不会立即设置 $scope.seasonDetails
的值,而是在收到响应后才会设置。
所以,是的,它不会在您调用 getSeasons
之后立即调用 console.log
,但一旦可用,它最终会到达那里.
如果您只需要数据在某个时候进入作用域(这样它就可以通过 ng-repeat
或类似的方式显示在您的页面中),那么您不需要做任何事情更多的。 Angular 将在更改到达时应用更改。
如果您确实需要操作结果,那么您可以直接在现有的 then
中进行操作,或者让 getSeasons
返回 $http
promise ,并在调用 getSeasons
后添加一个新的 then。哪个更相关取决于您的实际需求(例如,从多个地方调用 getSeasons,但您有不同的后处理,具体取决于从哪里调用它)。
选项 1:
var getSeasons = function() {
var data = "";
$http({
method: 'GET',
url: url
})
.then(function(response) {
var tvSeasonDetails = [];
for (var i = 0; i < response.data.seasons.length; i++) {
tvSeasonDetails.push(response.data.seasons[i].season_number)
}
$scope.seasonDetails = tvSeasonDetails;
console.log($scope.seasonDetails); //<----Variable displayed here
... add your call to any function that needs access to $scope.seasonDetails here...
})
}
选项 2:
var getSeasons = function() {
var data = "";
// the only change is right here
return $http({
method: 'GET',
url: url
})
.then(function(response) {
var tvSeasonDetails = [];
for (var i = 0; i < response.data.seasons.length; i++) {
tvSeasonDetails.push(response.data.seasons[i].season_number)
}
$scope.seasonDetails = tvSeasonDetails;
console.log($scope.seasonDetails); //<----Variable displayed here
})
}
getSeasons().then(function()
{
... your call to whatever function needs $scope.seasonDetails here ...
});
关于javascript - 如何用 'http get' 更新 $scope 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42988930/