Angular 2 - 日期管道异常:检查后表达式已更改

Angular 2 - Date pipe exception: Expression has changed after it was checked

我在我的组件中使用 DatePipe 将时间戳转换为可读的表达式。但是一旦文档被加载,我就会得到异常:

EXCEPTION: Error in http://localhost:3000/app/interest/user-interest.component.html:15:15 caused by: Expression has changed after it was checked. Previous value: '6 бер. 2017'. Current value: '5 бер. 2017'.

任何人都可以向我解释这里发生了什么。这是基本代码:

用户-interest.component.html

<p md-line>{{getFolderLastLearningSessionDate(folder.learningSessions)}}</p>

用户-interest.component.ts

getFolderLastLearningSessionDate(sessions:Array<LearningSession>):string {
    if (sessions)
      try {
        return this.learningSessionService.getLearningSessionDate(this.learningSessionService.getLastLearningSession(sessions));
      } catch (ex) {
        console.log(ex);
      }
    else return "Folder have not bean studied yet";
  }

学习-sessions.service.ts

public getLearningSessionDate(session:LearningSession):string {
    let datePipe = new DatePipe("uk-UA");
    return datePipe.transform(session.sessionDate);
  }
public getLastLearningSession(sessions:Array<LearningSession>):LearningSession {
    if (sessions) {
      return sessions.sort(
        (session1:LearningSession, session2:LearningSession) => {
          return session2.sessionDate.getDate() - session1.sessionDate.getDate();
        }).shift();
    }
    else
      throw new Error("folder is not studied yet");
  }

当变化检测导致模型发生变化时会抛出此错误。

在 devMode Angular 中,在第一个回合之后进行额外的变化检测回合,并检查模型是否在第一回合和第二回合之间发生了变化。如果是,那么您会收到您提到的错误消息。

在您的情况下,这可能是由于绑定到一个方法造成的,该方法在后续调用中 return 具有不同的值

{{getFolderLastLearningSessionDate(folder.learningSessions)}}

绑定到方法是有问题的,特别是如果后续调用可以 return 不同的值(具有相同属性和相同 属性 值的不同对象实例被认为是不同的)。

因此最好注册一些事件处理程序并更新此类事件处理程序中的 class-字段,然后绑定到 class-字段。