Search code examples
javascriptangulartypescriptrxjsobservable

Getting data from observables sync. Angular


I am trying to get data from observable. In the subscribe() method I can access this data. But to transfer the response to a global variable does not work. How can I do this?

Service:

getProducts():Observable<IProduct[]>{
  return <Observable<IProduct[]>> this.db.collection('products').valueChanges();
}

component:

products!: IProduct[];

constructor(private dataService: DataService){}

ngOnInit(): void {
  this.dataService.getProducts().subscribe(response => {
    console.log(response); // return data
    this.products = response;
  })

  console.log("products: ", this.products) // return undefined
  
  setTimeout(() => {
    console.log("products: ", this.products) // return data
  },1000)
}

I tried to display data in html *ngFor="let item of (products | async)" but it does not work


Solution

  • Your console.log will return undefined because it is executed before the subscribe is finished. Also you do not need async keyword in html when you do subscribe already. So you have to options:

    this.dataService.getProducts1().subscribe(response => {
        console.log(response); // return data
        this.products = response;
      });
    
      And in html:
      *ngFor="let item of products"

    Or you can use observable and async keyword in html:

    products: Observable<IProduct[]>;
    
    var products = this.dataService.getProducts();
    
      And in html:
      *ngFor="let item of (products | async)"

    If you need to better understand why there is data in setTimeout then research Microtask and Makrotasks in Angular and in which order it is executed.