0

I'm trying to get an array of objects from an API call and save it to a component variable. However, when assigning in a function, the value stays local. For example:

export class ItemsComponent implements OnInit {
  items: Item[];

  constructor(private ProductInformation: ProductInformationService) { }

  ngOnInit() {
    this.getProducts();
    console.log(this.items);   //undefined
    this.items = MOCK_ITEMS;
    console.log(this.items);   //correct 3 items
  }

  getProducts() {
    this.ProductInformation.getAllProducts(
      (response) => {
         this.items = response
         console.log(this.items);   //correct 3 items
      }
    );
  }
}

Why is items undefined after calling getProducts()? Why does it only get saved locally, and how can I get it to work?

xyz
  • 186
  • 1
  • 3
  • 19
  • You are trying to use an asynchronous operation synchronously. Where you are logging `this.items` and getting undefined, is because `getAllProducts` hasn't returned yet. –  Dec 12 '18 at 19:21
  • This is not Typescript scope problem. This is just because your "getProducts" is async. – Gilsdav Dec 12 '18 at 19:22
  • Please read through the suggested duplicate and answer. The answer explains very well how asynchronous calls work in javascript (and by extension Typescript). Without a good understanding of this core concept you won't get very far as a javascript programmer, it is worth the time. – Igor Dec 12 '18 at 19:23

1 Answers1

1

It's nothing to do with the scope. If you look at your getProducts method it is asynchronous call. you will get the response after some time. So when you immediately put the console.log(this.items); it becomes undefined.

When you place the console.log() inside the subscribe, you are waiting until you get the response. so you see the items defined there. same goes with Mock items, as you have the items there you see the elements in the console.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396