我无法使用 http get on angular 的结果

i can't use the result of http get on angular

大家早上好
我不能使用这个请求的结果(我想在局部变量中使用它)
这是我放在 ngOnInit

中的代码
  appli:any=[];
  ngOnInit() {

    this.http.get<any>(this.url).subscribe(data => {
      console.log(data) //returns data
      for (let item of data) {
        this.appli.push(item)
      }
      console.log(this.appli) //returns data
    });
    console.log(this.appli) //returns data
    console.log(this.appli[0]) //returns undefined
    console.log(this.appli.length)// returns 0

  }


这是您使用可观察对象时的默认行为。

console.log(this.appli[0]) //returns undefined
console.log(this.appli.length)// returns 0

以上行返回 undefined 和 0,因为它们在 Subscribe 函数的范围之外,甚至会在收到 API 响应之前执行。 this.http.get returns 可观察且不会停止代码执行。

我很确定连线:

console.log(this.appli) //returns data

将 运行 在 API returns 之前回复。

如果您将以上控制台语句放在订阅函数中,这些将打印正确的输出。

Http 调用是异步的,因此块外的语句将首先执行,然后在数据到达时执行 http 块内的语句

另一种等待数据的方法是使用async-await

Oninit(){
 getAsyncData();
}

 async getAsyncData() {
    this.asyncResult = await this.http.get<any>(this.url).toPromise();
    // execution of this statement will wait until promise is resolved..');
    // now you can do anything with your data i.e stored in this.asyncResult and it will get executed after the data arrives 
  }

有关更多说明和详细信息,您还可以查看以下内容link

https://medium.com/@balramchavan/using-async-await-feature-in-angular-587dd56fdc77

来自 HTTP 客户端的响应是异步的。请参阅 here 了解更多信息。

这意味着所有依赖于 HTTP 响应的逻辑都应该移到订阅中。旁注,<any> 可以在这里删除,它没有定义任何特定的对象模型。如果多个组件需要来自 this.url 的数据,最好处理来自服务的 HTTP 调用。处理错误也是一个好习惯。

以下应该有效

ngOnInit() {
  this.http.get<any>(this.url).subscribe(
    data => {
      console.log(data);
      for (let item of data) {
        this.appli.push(item);
      }
      console.log(this.appli);

      console.log(this.appli[0]);
      console.log(this.appli.length);
    },
    error => {
      // handle error
    }
  );
}

如果你想迭代模板中的数组,你可以尝试以下

控制器

app: any;

ngOnInit() {
  this.http.get(this.url).subscribe(
    data => { this.app = data; },
    error => { // handle error }
  );
}

模板

<ng-container *ngIf="app">
  <div *ngFor="let item of app">
    {{ item }}
  </div>
</ng-container>