如何解决Angular EventEmitter 不会发出数组的任何变化
这是我的代码:
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);显示在浏览器中加载后数组为空。
解决方法
问题在于 getNotes()
方法。它通过调用 getData()
发送异步请求,不等待结果并且可以返回一个空列表(如果它没有时间完成)或来自服务器的数据(您有时通过浏览看到的) )。方法是订阅后在notes
中返回getData()
。
console.log('getNotes()',this.notes);在对 api 的 getData 调用获取结果之前触发。这就是为什么您在页面加载的登录中没有得到任何信息的原因。
你能显示notes.component.html吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。