0

Is there a clever way to check if api get loaded before any operation on the object which comes from the backend is done?

Example:

 ngOnInit() {
    this.guideService.getAll()
      .subscribe(res => {
        this.guides = res;
      });
  }

...and

 checkIfSaveButtonCanBeDisabled(){
    console.log('checkIfSaveButtonCanBeDisabled');
    if(this.guides){
      for (let i = 0; i < this.guides.length; i++) {
        if(!this.guides[i].confirm){
          return false;
        }
      }
      return true;
    }
    return false;
  }

and without if statement if(this.guides){} I get this.guides.length is undefined. The case is quite important because there could be other examples in project with similar case.

bielas
  • 672
  • 2
  • 12
  • 29
  • When doing inside callback (subscribe) you are sure that you have your data: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – AT82 Oct 12 '17 at 12:06
  • So you mean that every operation I should do inside the callback..?! – bielas Oct 12 '17 at 12:10
  • @bielas correct, you want to wait for guides to be populated before performing any operation on it. – LLai Oct 12 '17 at 13:05

0 Answers0