繁体   English   中英

Angular EventEmitter 不会发出数组的任何更改

[英]Angular EventEmitter does not emit any changes of an array

这是我的代码:

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>

在浏览器中加载后不会显示注释,只有当我导航离开然后 go 回到注释时,才会显示它们。

console.log('getNotes()', this.notes); 显示在浏览器中加载后数组为空。

问题出在getNotes()方法上。 它通过调用getData()发送一个异步请求,不等待结果,并且可以返回一个空列表(如果它没有时间完成)或来自服务器的数据(您有时通过浏览看到的内容)。 go 的方法是订阅后在getData()中返回notes

console.log('getNotes()', this.notes); 在对 api 的 getData 调用获得结果之前触发。 这就是为什么您在页面加载日志中没有得到任何信息的原因。

你能显示 notes.component.html 吗?

暂无
暂无

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

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