【问题标题】:amTimeAgo with observable - constant refreshing every 1samTimeAgo 与 observable - 每 1 秒不断刷新
【发布时间】:2017-04-22 04:57:19
【问题描述】:

使用

"angular2-moment": "^1.3.3",
"moment": "^2.18.1",

当我在模板中使用amTimeAgo 管道时:

<div *ngFor="let issue of getIssues() | async ">
  {{ issue.time | amTimeAgo }}
  <!--{{ issue.time | amUtc }}-->
  <!--{{ issue.time | amLocal }}-->
  <p>{{ issue.time | amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a' }}</p>
  {{ issue.time }}
  {{issue | json }}
</div>

,具有可观察性:

getIssues(): Observable<any[]> {

  return Observable.of([
    {
      name: "1",
      time: new Date(),
    },
    {
      name: "2",
      time: new Date(),
    },
    {
      name: "2",
      time: new Date(),
    }
  ]);
}

常量每秒刷新一次(每次都是 new new Date())。

如何预防?

为什么每次都获取新数据?

我不想每次都有新数据。另外,这将是一个 HTTP 调用,因此很昂贵。

我猜更改检测被触发太频繁了...

我检查的其他管道似乎不会导致问题(例如 amDateFormat)

【问题讨论】:

  • I guess change detection is triggered too often... 这是正确的。有很多事情会触发变更检测周期。事实上,您可能会对它的触发频率感到非常惊讶。
  • 我认为变更检测是由amTimeAgo 管道触发的。
  • 很有可能。我希望你可以配置事件的间隔,因为频繁的事件可能会影响整个组件的性能。特别是,如果您的页面计算量很大...

标签: angular momentjs angular-moment angular-pipe


【解决方案1】:

您的getIssues() 方法在每次被调用时都会创建一个新的Observable。只要 Angular 出于某种原因执行变更检测,就会调用该方法。您可能有一些事件源(可能是一些计时器或鼠标事件处理程序)触发更改检测,以便刷新时间值。您可以只使用您发布的代码和一个按钮(和一个单击处理程序)创建一个简单的页面 - 当您单击按钮时,时间会刷新。

所以唯一需要做的就是将 observable 分配给本地属性。

async 管道调用ChangeDetectorRef.markForCheck(),它告诉 Angular 的更改检测该组件可能有更改。更多详情请参阅以下文章:

【讨论】:

    【解决方案2】:

    为什么不在组件生命周期的 Init 步骤创建一个时刻的快照,然后在多个结果中重用它(假设之后没有代码会改变日期对象)?

    currentDate: Date;
    
    ngOnInit(): void {
      this.currentDate = new Date();
    }
    
    getIssues(): Observable<any[]> {
      return Observable.of([
        {
          name: "1",
          time: this.currentDate,
        },
        {
          name: "2",
          time: this.currentDate,
        },
        {
          name: "2",
          time: this.currentDate,
        }
      ]);
    }
    

    在这里使用ngOnInit 而不是构造函数很重要。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多