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

}

1 Answer 1

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();
    });
  }
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Rephrased: Can I wait and check for the data to be loaded to call my method afterwards?
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.
Fair enough, I'll try googling now that I know the problem. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.