-1

So in my angular project i created a service which contains a method with http get request as follows:

  getAllProducts(){
return this.http.get<IProduct[]>(this.baseUrl + 'products/all');}

In another component I want to get the IProduct[] array using the service. So inside the component I have

ngOnInit(): void {
   
    this.update();
  }
  update(): void{
    this.adminService.getAllProducts().subscribe(response =>
      {
       this.allProducts = {...response};
       console.log(this.allProducts); //Returns a filled array
      }, error => {
        console.log(error);
      });
    console.log(this.allProducts); //Returns undefined
  }

My question is: How can I copy the httpget result into my component's variable and dont loose it outside the observable scope?

1 Answers1

0

You get undefined because the http call returns an observable and you are mixing up sync and async programming. So what happens here is:

  1. onInit calls update()
  2. you subscribe to getAllProducts()
  3. The http call has not completed yet
  4. console.log() print an undefined array since the subscribe has not been executed yet
  5. subscribe triggers because the http call returns
  6. allProducts is assigned

What you want to do is execute your logic from inside the subscribe and if you have to use it in the html then you can use an ngIf if necessary.

ukn
  • 1,723
  • 1
  • 14
  • 24