0

In the GetAllMainStore() function, I am able to get the data from the API and the console (from the console.log within the function) shows that there is data in "this.MainStoreArray".

My issue is that when I try and access "this.MainStoreArray" outside of the GetAllMainStore() function, the array is empty. I cannot figure out why this is happening. The console.log that I ran in the ngOnInit function comes out as empty.

  ngOnInit() {

    this.CurrentStore = this.stateService.CurrentStore;
    this.CurrentMainStore = this.stateService.CurrentMainStore;

    this.stateService.CurrentStore = undefined;
    this.stateService.CurrentMainStore = undefined;

    this.GetAllMainStore();

    console.log(this.MainStoreArray);

    // this.EditStoreForm = this.formBuilder.group({
    //   storeId: [this.CurrentStore.storeId],
    //   storeName: [this.CurrentStore.storeName, Validators.required],
    //   storeLocation: [this.CurrentStore.storeLocation],
    //   storeRating: [this.CurrentStore.storeRating]
    // });

  }//ngOnInit

  GetAllMainStore() {

    this.dataService.GetAllMainStores().subscribe((data) => {

      this.MainStoreArray = data;

      console.log(this.MainStoreArray);

    });

  }// get Main Store

1 Answers1

0

This is how Asynchronous programming works, Any functionality that directly depends on an asynchronous data should be inside the subscription. If the next statement relies on a state inside the subscription it will not work. Here are more details

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396