Angular Subscribe 返回空数组[重复]

问题描述 投票:0回答:1

使用 http.get().subscribe 数据作为空数组返回,但是如果我在订阅代码中调用 console.log() ,数组将正确显示。

这是代码:

  public data: Noticia[] = [];
  public api = "http://localhost:3000/data"

  constructor(
    private httpClient: HttpClient
    ) { }

  ngOnInit() { 
        this.httpClient.get(this.api).subscribe((response: Noticia[]) =>{
        response.forEach(news =>{
          this.data.push(news);
        });
       
        console.log("data in subscribe", this.data);
      });
      console.log("data",this.data);
      console.log("data [0]",this.data[0]);
  }

这是控制台日志:

enter image description here

订阅结束后如何保留数据?

arrays angular subscribe
1个回答
-1
投票

这是很正常的,因为这两行在 subscribe() 之外。

console.log("data",this.data);

console.log("data [0]",this.data[0]);

根据您的代码,数组“data”将在填充之前被记录。

一旦可观察对象在订阅方法中得到解析,那么您将获得可用的数据。

在这种情况下,您只需移动下一个回调(在订阅方法中)中的两行即可获得此代码

ngOnInit() { 
     this.httpClient.get(this.api).subscribe((response: Noticia[]) =>{
     response.forEach(news =>{
         this.data.push(news);
      });
       
      console.log("data in subscribe", this.data);
      console.log("data",this.data);
      console.log("data [0]",this.data[0]);
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.