0

I am working on an angular app. I have an API call and a if statement in my ngOnInit() as follows:

  ngOnInit() {
      this.myService.getData(id).subscribe(res => {
        if (res != null) {
            this.myId = res.id;
         }
      }
      
    if (this.myId == 2) {
        //execute my code
     }
    }

The problem I am facing is this if a statement gets executed before I get the value of Id from API call and as a result, my code doesn't work. I tried putting if statement under setTimeout and the code worked. But I want to have some better solution instead of using setTimeout. How can I do that?

Rahul
  • 29
  • 5

1 Answers1

0

try this,

  ngOnInit() {
      this.myService.getData(id).subscribe(res => {
        if (res != null) {
            this.calculate(res.id);
         }
      }
 }
 calculate(id){
  if(id==2){
    //do something 
  }else{
    //do something else
  }
}

if your conditions exceed use switch case.

Zia
  • 506
  • 3
  • 20