2017-03-07 44 views
1

我在组件中使用DatePipe将时间戳转换为可读表达式。但是,一旦文件被加载,我得到的例外:Angular 2 - 日期管道异常:检查后表达式已更改

例外:http://localhost:3000/app/interest/user-interest.component.html:15:15错误造成的:表达式检查后发生了变化。以前的值:'6бер。 2017' 年。当前值:'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"); 
    } 

回答

3

如果更改检测导致模型发生更改,则会引发此错误。

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

你的情况,这可能是由绑定到在后续调用

{{getFolderLastLearningSessionDate(folder.learningSessions)}} 

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

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

相关问题