Search code examples
angularhttpclient

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


Good morning all
I can't use the result of this request(i want use it in a local variable)
here is my code that i put in 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

  }



Solution

  • Http calls are async so the statements outside the block will be executed first then the ones inside the http block when the data arrives

    The other way to wait for data is to use 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 
      }
    

    For more clarification and details you can check the following link as well

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