如何使用'http get'更新$ scope变量?

时间:2017-03-23 23:40:05

标签: javascript angularjs http asynchronous scope

努力理解http请求和承诺的概念。我知道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

2 个答案:

答案 0 :(得分:4)

正如您所指出的,$http.get()是异步的。因此,当您调用getSeasons时,它不会立即设置$scope.seasonDetails的值,而只会在收到响应之后。

所以,是的,在您致电console.log之后,在getSeasons致电ng-repeat时,它无法使用,但一旦可用,它将最终到达。< / p>

如果您只是需要数据在某个时间点进入范围(因此可以通过then等显示在您的页面中),那么您不需要再做任何事情了。 Angular将在到达时应用更改。

如果您确实需要操作结果,那么您可以直接在现有getSeasons中执行此操作,或让$http返回getSeasons承诺,然后添加新的您致电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... }) } 。哪个更相关取决于您的实际需求(例如,从几个地方调用getSeasons,但根据调用的位置或不调用,您有不同的后处理。)

选项1:

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 ...
});

选项2:

{{1}}

答案 1 :(得分:1)

如果您需要在seasonDetails更改后操作某些结果,则可以使用函数$scope.$watch(...)

 $scope.$watch('seasonDetails', function(newValue, oldValue) {
      console.log($scope.seasonDetails);
 });