简体   繁体   English

Angular-无法查看Angular2如何自动更新服务中的数据

[英]Angular - Cannot see how Angular2 auto updates data from service

I am an Angular2 beginner, creating a test note-taking app. 我是Angular2初学者,创建了一个测试笔记应用程序。 The app is simple: I have a NotesContianerComponent which connects to a NoteService which has the getNotes() and addNote() method. 该应用程序是简单的:我有一个NotesContianerComponent其连接到一个NoteService其具有getNotes()addNote()方法。

In the NotesContainerComponent , I am storing the data returned from service in a member myNotes and on ngOnInit event, refreshing the array. NotesContainerComponent ,我将从服务返回的数据存储在成员myNotesngOnInit事件中,以刷新数组。 I am not touching that array anywhere in that code as of now. 到目前为止,我尚未在该代码的任何地方触摸该数组。

Now, when I add a new note using the form and call the service's addNote() method from the NotesContainerComponent , the note does get added to the backend mock notes array, but at the same time the UI (ie NotesContainerComponent ) gets updated with the new note automatically! 现在,当我使用该表单添加新笔记并从NotesContainerComponent调用服务的addNote()方法时,该笔记确实会添加到后端模拟笔记数组中,但与此同时,UI(即NotesContainerComponent )会使用新笔记自动! I am not doing anything to refresh it manually. 我没有做任何手动刷新的事情。

To investigate, I added a console.log() to the getNotes method of the service, however it is being only called the first time, possibly by ngOnInit hook. 为了进行调查,我在服务的getNotes方法中添加了console.log() ,但是它只是第一次被调用,可能是通过ngOnInit钩子调用的。

What I cannot figure out is, how does Angular2 know about the new note without even querying the service automatically? 我不知道的是,Angular2如何在不自动查询服务的情况下知道新笔记? And how to stop this? 以及如何停止呢? Any clues will be appreciated. 任何线索将不胜感激。

NotesContainerComponent code for reference: 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);
    }
}

If you are storing your mock data in an Object or an Array and this.myNotes 's reference is that Object s reference. 如果要将模拟数据存储在ObjectArray ,则this.myNotes的引用是该Object的引用。 When your mock datas content changes, all the references will change too. 当您的模拟数据内容更改时,所有引用也会更改。 This is because objects are mutable in javascript. 这是因为对象在javascript中是可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM