Search code examples
javascriptangularasynchronousrxjsobservable

Angular call to REST API not waiting for the data to arrived


I have the following code:

export class Whatever implements OnInitn{

    prices;

     ngOnInit(){
       this.CoinPricesService.getPrices().subscribe(
           pricesFromResponse => {
             this.prices = pricesFromResponse;
              console.log('this is what I get from the api: ', this.prices);
           }
       );
       
      console.log('this is my prices class object', this.prices);
     }
}

the output is this:

this is my prices class object undefined

api: this is what I get from the $, $ $

as you can see the first message is showing in second and the second is in the first place with an UNDEFINED, obviously what is happening is that the code is not waiting for the response to come, is being sychronous, WHY ? isn't observable.Subscribe(response ==> this.myVar = response); meant to take care of that ? I can't use the data in other places of my class because it's always undefined when the codes hits there, please help

My Service Looks like this:

@Injectable({
  providedIn: 'root'
})
export class CoinPricesService {

  private apiURl = 'https://api.forprices/blablabla';

  constructor(private http: HttpClient) { }

  getPrices(){
    return this.http.get<any>(this.apiURl);
  }
}

Solution

  • If you had a function that depended on price, then you could execute the functions within the subscribe. something like this:

    export class Whatever implements OnInitn {
    
        prices;
    
        ngOnInit() {
            this.CoinPricesService.getPrices().subscribe(
                pricesFromResponse => {
                    this.prices = pricesFromResponse;
                    console.log('this is what I get from the api: ', this.prices);
                    this.someFunction(this.prices);
                }
            );
        }
        
        someFunction(prices: any) {
            //use prices ...
        }
    }