我是Angular2初學者,創建一個測試筆記應用程序。該應用程序很簡單:我有一個NotesContianerComponent
連接到NoteService
其中有getNotes()
和addNote()
方法。Angular - 無法看到Angular2自動更新服務中的數據
在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);
}
}
'myNotes'是指只能通過'getNotes()'方法更新的組件中的局部數組..所以不能這樣嗎? –
@aditya_m就是這種情況。你用'add'方法更新它,並更改數組。由於'this.myNotes'指向這個本地數組,它也會改變。 – echonax
'add'方法屬於服務,它更新服務中存在的模擬數組,而不是組件的本地數組 –