Robin
Robin

Reputation: 51

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?
    });
  }

}

Upvotes: 3

Views: 164

Answers (1)

Sefa
Sefa

Reputation: 8992

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();
    });
  }

Upvotes: 3

Related Questions