【问题标题】:Angular 2 - Date pipe exception: Expression has changed after it was checkedAngular 2 - 日期管道异常:检查后表达式已更改
【发布时间】:2017-07-28 01:16:16
【问题描述】:

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

异常:http://localhost:3000/app/interest/user-interest.component.html:15:15 中的错误由以下原因引起:表达式在检查后已更改。以前的值:'6 бер。 2017 年'。当前值:'5 бер。 2017 年。

任何人都可以,请解释一下这里发生了什么。这是基本代码:

用户兴趣.component.html

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

user-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";
  }

learning-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");
  }

【问题讨论】:

    标签: angular angular2-pipe


    【解决方案1】:

    当更改检测导致模型发生更改时会引发此错误。

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

    在您的情况下,这可能是由于绑定到在后续调用中返回不同值的方法

    {{getFolderLastLearningSessionDate(folder.learningSessions)}}
    

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

    因此最好注册一些事件处理程序并在此类事件处理程序中更新类字段并绑定到类字段。

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 2017-05-08
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2017-08-28
      • 2018-12-19
      相关资源
      最近更新 更多