角度6:OnChanges不适用于异步管道

时间:2018-08-08 09:08:39

标签: angular

我有一个组件需要跟踪对数据源的更改。父组件通过异步管道提供数据。如果更改了数据源(添加或删除了项目),则不会触发ngOnChanges。

帮助解决问题。

@Component({
  selector: 'app-todo',
  template: `
<div>
  <button (click)="addTodo()">Add Item</button><br />

    <div *ngFor="let todo of todos">
        {{ todo.value }} <button (click)="deleteTodo(todo.id)">x</button>
    </div>
</div>
`
})
export class TodoComponent implements OnChanges {
  @Input() todos: Todo[];

  constructor(private todoService: TodoService) {
  }

  addTodo() {
    this.todoService.create({ value: 'value '+this.todos.length });
  }

  ngOnChanges(changes: { [key: string]: SimpleChange })
  {
    if (changes['todos']) { 
      console.log('todos changed')
    }
  }

  deleteTodo(todoId: number) {
    this.todoService.remove(todoId);
  }
}

父组件:

@Component({
  selector: 'my-app',
  template: `
<h1>Angular Observable Data Services</h1>

<p>Only implimented a simple post and delete</p>

<h3>Component 1</h3>
<app-todo [todos]='todos | async'></app-todo>

<br /><br />

<h3>Component 2</h3>
<app-todo [todos]='todos | async'></app-todo>
`
})
export class AppComponent  {
  todos: Observable<Todo[]>;

  constructor(private todoService: TodoService){
    this.todos = this.todoService.todos;

    this.todoService.loadAll();
  }
}

stackblitz

1 个答案:

答案 0 :(得分:2)

您遇到的是浅层克隆/深层克隆问题。

例如,在您的服务create方法中,您复制了this.dataStore,但随后重用了未被复制的todos属性,它保持相同的引用,因此没有任何触发{ {1}}。

您要执行的操作类似于:

onChange

并将其输入您的this.dataStore.todos.push(something); //this mutates an array const x = [...this.dataStore.todos];`//clones actual array

有用的参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Deep_Clone