Angular 2+ Expression has changed after it was che

2019-08-28 06:33发布

问题:

I know there are several threads on this issue, but the proposed fixes are not working for me. The data appears correctly then soon dissappears.

From what I understand, a round of change detection needs to be activated. I have used:

  ngAfterViewInit() {
      this.cdr.detectChanges();
  }

but the error persists. If I add this.cdr.detectchanges() call to the increment() method, it produces an loop and the maximum call stack is exceeded.

component.html:

 <div *ngFor="let item of messageSplit[increment()]">
      <td>{{item}}</td>
 </div>

relevant component.ts:

ngAfterViewInit() {
  this.cdr.detectChanges();
}

setContainer(container: string) {
  this.messageContainer = container;
}


loadMessages() {
  this.messageSplit = [];
  const currentUserId = +this.authService.decodedToken.nameid;
  this.userService.getMessages(this.authService.decodedToken.nameid,
  this.messageContainer)
  .do(messages => {
    _.each(messages, (message: Message) => {

      if (this.messageContainer !== 'unread') {
        if (this.compareArray(message) !== true) {
          this.splitMessages(message);
        }
      }
      if (message.isRead === false && message.recipientId === currentUserId) 
 {
        this.userService.markAsRead(currentUserId, message.id);
      }
    });
  }, error => {
    console.log('');
  }, () => {
    console.log(this.messageSplit);
    this.splitReady = true;
  })
  .subscribe((res: Message[]) => {
    this.messages = res;
  });
 }

compareArray(message) {
  let count = 0;
  for (let i = 0; i < this.messageSplit.length; i++) {
    if (message.content !== null) {
      if (this.messageSplit[i] === message.content.split(',')) {
        count = count + 1;
      }
    }
  }
    if (count > 0) {
      return true;
    }
    return false;
}

splitMessages(message) {
  if (message.content !== null) {
    this.messageSplit.push(message.content.split(','));
  }
}

increment() {
  return this.counter++;
}

My goal is to have each of the sub items displayed in a in the table