Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading