Angular - 看不到 Angular2 如何从服务自动更新数据

Angular - Cannot see how Angular2 auto updates data from service

我是 Angular2 初学者,正在创建一个测试笔记应用程序。该应用程序很简单:我有一个 NotesContianerComponent,它连接到具有 getNotes()addNote() 方法的 NoteService

NotesContainerComponent 中,我将从服务返回的数据存储在成员 myNotes 中,并在 ngOnInit 事件中刷新数组。到目前为止,我没有在该代码的任何地方触及该数组。

现在,当我使用表单添加新笔记并从 NotesContainerComponent 调用服务的 addNote() 方法时,笔记确实被添加到后端模拟笔记数组中,但同时时间 UI(即 NotesContainerComponent)自动更新为新笔记!我没有做任何事情来手动刷新它。

为了调查,我在服务的 getNotes 方法中添加了一个 console.log(),但是它只是第一次被调用,可能是通过 ngOnInit 挂钩。

我不明白的是,Angular2 是如何在不自动查询服务的情况下知道新笔记的?以及如何阻止这种情况?任何线索将不胜感激。

NotesContainerComponent代码参考:

export class NotesContainerComponent implements OnInit {
    constructor(
        private noteService: NoteService
    ) { }

    addNote(newNote):void {
        this.noteService.add(newNote);
    }

    myNotes: Notes[];

    ngOnInit() {
        this.noteService.getNotes()
            .then(notes => this.myNotes = notes);
    }
}

如果您将模拟数据存储在 ObjectArray 中,并且 this.myNotes 的引用就是 Object 的引用。当您的模拟数据内容发生变化时,所有引用也会发生变化。这是因为对象在 javascript.

中是可变的