3

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

}
Robin
  • 51
  • 3

1 Answers1

3

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();
    });
  }
Sefa
  • 8,865
  • 10
  • 51
  • 82
  • Thanks for the fast reply. Can I make the loadData method synchronous somehow? I have 2 methods loading 2 different arrays of objects and I need to iterate over both arrays at once after they've been loaded. I'd hate to mix them up by loading them in a single method. – Robin Oct 31 '16 at 12:35
  • Rephrased: Can I wait and check for the data to be loaded to call my method afterwards? – Robin Oct 31 '16 at 12:40
  • 1
    I made a quick research about it sometime ago and as far as i know there is no way waiting for async functions. You are meant to implement logic in callback functions. You might wanna google it see if things have changed or not. – Sefa Oct 31 '16 at 12:43
  • Fair enough, I'll try googling now that I know the problem. Thanks! – Robin Oct 31 '16 at 12:46