异步调用后,AngularJS Scope在视图中未更新 [英] AngularJS Scope not updating in view after async call

查看:84
本文介绍了异步调用后,AngularJS Scope在视图中未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向API发出请求时,无法在前端更新我的范围.在后端,我可以看到$ scope变量的值正在更改,但这并没有反映在视图中.

I am having trouble updating my scope on the front-end while making a request to an API. On the backend I can see that the value of my $scope variable is changing but this is not being reflected in the views.

这是我的控制者.

Controllers.controller('searchCtrl', 
 function($scope, $http, $timeout) {
   $scope.$watch('search', function() {
      fetch();
   });

 $scope.search = "Sherlock Holmes";

 function fetch(){
   var query = "http://api.com/v2/search?q=" + $scope.search + "&key=[API KEY]&format=json";
    $timeout(function(){
      $http.get(query)
      .then(function(response){ 
        $scope.beers = response.data; 
        console.log($scope.beers);
      });
    });  
 }
});

这是我的html的代码段

Here is a snippet of my html

<div ng-if="!beers">
  Loading results...
</div>
<p>Beers: {{beers}}</p>
<div ng-if="beers.status==='success'">

  <div class='row'>
    <div class='col-xs-8 .col-lg-8' ng-repeat="beer in beers.data track by $index" ng-if="beer.style">
    <h2>{{beer.name}}</h2>          
    <p>{{beer.style.description}}</p>
    <hr>
    </div>
  </div>
</div>

<div ng-if="beers.status==='failure'">
  <p>No results found.</p>
</div>

我尝试了几种解决方案,包括使用 $ scope.$ apply(); ,但这只会造成常见错误

I've tried several solutions including using $scope.$apply(); but this just creates the common error

错误:$ digest已经在执行中

Error: $digest already in progress

以下帖子建议使用 $ timeout 或$ asyncDefault AngularJS:防止错误$ digest在进行时调用$ scope.$ apply()

The following post suggested to use $timeout or $asyncDefault AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

我上面的代码使用$ timeout,并且没有错误,但视图仍未更新.

The code I have above uses $timeout and I have no errors but still the view is not updating.

感谢帮助

推荐答案

如果您使用的是AngularJS 1.3+,则可以在$scope.beers = response.data;语句后立即尝试$scope.$applyAsync().

I you are using AngularJS 1.3+, you can try $scope.$applyAsync() right after $scope.beers = response.data; statement.

这是Angular文档所说的$applyAsync()

This is what Angular documentation says about $applyAsync()

安排$ apply的调用在以后发生.实际的时差会因浏览器而异,但通常约为10毫秒. 来源

更新

正如其他人指出的那样,您通常不必(通常)手动触发摘要循环.在大多数情况下,它只是指向您的应用程序的不良设计(或至少不是AngularJS友好的设计).

As others have pointed out, you should not (usually) need to trigger the digest cycle manually. Most of the times it just points to a bad design (or at least not an AngularJS-friendly design) of your application.

当前在OP中,在$ watch上触发fetch方法.相反,如果该方法由ngChange触发,则摘要循环应自动触发.

Currently in the OP the fetch method is triggered on $watch. If instead that method was to be triggered by ngChange, the digest cycle should be triggered automatically.

以下是这样的代码的示例:

Here is an example what such a code might look like:

HTML

// please note the "controller as" syntax would be preferred, but that is out of the scope of this question/answer
<input ng-model="search" ng-change="fetchBeers()">

JavaScript

function SearchController($scope, $http) {

    $scope.search = "Sherlock Holmes";

    $scope.fetchBeers = function () {
        const query = `http://api.com/v2/search?q=${$scope.search}&key=[API KEY]&format=json`;
        $http.get(query).then(response => $scope.beers = response.data);
    };

}

这篇关于异步调用后,AngularJS Scope在视图中未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆