Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 TS object array only defined while subscribed to service

I'm in the process of learning Angular 2 using TypeScript. So far I've written a little API service that uses HTTP get method to feed me json data using observables. Everything is working fine, I can use the data in my view, I can also use the data in my component, but only while I'm subscribed to the getData() method.


Why is that and what other possibilities do I have to make the object array available to all methods in my component for easy iteration and management?

Example component:

export class SomeComponent implements OnInit {

  public someData: DataObject[];

  public constructor(private service: SomeService) {}

  public ngOnInit(): void {
    this.loadData();
    this.useData();
  }

  private loadData(): void {
    this.service.getData().subscribe(data=> {
      this.someData = data;

      this.someData.forEach(dataObject => {
        // this works fine
      });
    });
  }

  private useData(): void {
    this.someData.forEach(dataObject => {
      // dataObject is (of type?) undefined, why?
    });
  }

}
like image 550
Robin Avatar asked Dec 07 '25 16:12

Robin


1 Answers

It's because http calls are async. Your this.useData(); does not wait this.loadData(); to finish. This should work:

  private loadData(): void {
    this.service.getData().subscribe(data=> {
      this.someData = data;

      this.useData();
    });
  }
like image 108
Sefa Avatar answered Dec 10 '25 07:12

Sefa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!