这是我的代码:
notes.service.ts
private notes: Array<Note> = [];
notesChanged = new EventEmitter<Note[]>();
getNotes() {
this.getData();
console.log('getNotes()', this.notes);
return this.notes;
}
getData() {
this.http.get<Note[]>(this.url).subscribe(
(data) => {
this.notes = data;
this.notesChanged.emit(this.notes);
}
);
}
notes.component.ts
notes: Array<Note> = [];
ngOnInit(): void {
this.notes = this.notesData.getNotes();
this.notesData.notesChanged.subscribe(
(notes: Note[]) => this.notes = notes
);
}
notes.component.html
<div *ngFor="let item of notes" class="col-md-4">
<a [routerLink]="['/note', item.id]" class="note-link">
<div class="note-body text-center">
<h4>{{item.title}}</h4>
<p>{{item.text}}</p>
</div>
</a>
</div>
在浏览器中加载后不会显示笔记,只有当我离开然后返回笔记时,才会显示它们。
console.log('getNotes()', this.notes); 显示在浏览器中加载后数组为空。