javascript - AngularJs,使用 $interval 定期刷新 View 不会更新某些值

标签 javascript angularjs

假设您有一个 View ,其中填充了对某些服务的 http 调用,该服务返回要显示的对象列表。我想定期刷新这些数据。我发现 $interval 可以完成该行为。

问题是我无法在每次刷新 View 时都显示一个简单的“正在加载”屏幕。

我想过类似的事情:

   viewModel.isLoading = true;
   viewModel.refreshView();
   viewModel.isLoading = false;

当然,isLoading 绑定(bind)到一些带 Angular View 消息。这不起作用,该属性始终为假。我发现是因为angular在$interval调用的函数退出的时候通知view属性改变了,但是退出的时候isLoading一直是false。

我怎样才能使 isLoading 反射(reflect)它的变化,即使它在函数内部也是如此?


Plunker 片段(Angular 1.6.0):http://plnkr.co/edit/kIANiq6F0eM98KgHdr6i?p=preview

我的看法:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
    <script src="testController.js"></script>
</head>

<body>

    <div ng-app="testApp">
      <div ng-controller="testController as viewModel">

          <h1>
          "IsLoading" value: {{ viewModel.isLoading }}
          </h1>

      </div>
    </div>

</body>

我的 Controller :

(function() {

angular.module('testApp', [])
.controller("testController", testController);

function testController($interval) {

  viewModel = this;
  viewModel.isLoading = true;

  viewModel.refreshView = function () {

      viewModel.DoSomeLongRunningOperation();

  };

  viewModel.DoSomeLongRunningOperation = function() {
      // 
  }


   var invertPropertyTimer = $interval(function () {

    viewModel.isLoading = true;
    viewModel.refreshView();
    viewModel.isLoading = false;

   }.bind(this), 1000);


}

})();

最佳答案

我不确定这个,但是使用 promises 怎么样?

您可以在 refreshView 函数中返回一个 promise 对象。这将帮助您在稍后的时间间隔内查看任务是否在您的 DoSomeLongRunningOperation 函数中完成。

  viewModel.refreshView = function () {
  return new Promise(function(resolve, reject){
          viewModel.DoSomeLongRunningOperation();
          resolve();
      });
  };

在你的操作函数中做一些任务。假设有一个操作需要 200 毫秒。 (我使用了 setTimeout 但 angular 也有自己的可测试 $timeout 服务。)

  viewModel.DoSomeLongRunningOperation = function() {
      //do your thing.  

      setTimeout(function(){
            console.log("timeoutends.")
      }, 200);
  }

在您的界面中,使用 then() 听取 promise 并更改 isLoading 变量。该 promise 解析器将在 DoSomeLongRunningOperation 函数完成后触发;

var invertPropertyTimer = $interval(function () {

  viewModel.isLoading = true;
    viewModel.refreshView().then(() =>{
      viewModel.isLoading = false;
    });

}.bind(this), 1000);

我还没有检查它是否有效或语法是否正确。如果数据在变化但 View 没有变化,您可能还需要使用 $apply()


链接:

关于javascript - AngularJs,使用 $interval 定期刷新 View 不会更新某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538299/

相关文章:

javascript - 如何在 html5 和 WebGL 中从 ArrayBuffer 创建纹理

javascript - 将 localtunnel\ngrok 与多个本地站点一起使用

javascript - Firebase 文件上传进度从 0 跳到 100

javascript - 如何使用angularjs从表中删除行

javascript - Karma 启动器 HTML5 API

javascript - Angular 和 Asp.Net Mvc 错误

javascript - 使用 Node 、mysql、express 和纯 js 从数据库中删除一行

javascript - 动态添加/删除元素

javascript - 在 AngularJS Controller 内的循环中渲染和注入(inject)动态模板

angularjs - 如何在 ionic 2 中插入视频列表?