-2

I have a component class and service class. I have the logic of flipping a flag when http 200 status code is received. Based on the response received, I flip the flag using an if condition.

Requests(data:Array<String>):Observable<any>{
    return this.http.post(this.Url,data)
      .map(
        (res:Response) => {
          if(res.status === 200 || res.status===201) {
            return res.json()
          }
        }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }

The component file goes like this.

methodName(selectedData){

    this.service.Requests(Id).subscribe((Response => {
      this.rResponse = Response;

    }));
    if(rResponse){
    // My logic to flip the flag
        }
      }
    }
    }

So based on the response received from service, I will flip the flag.

But when I run my code in debugger tools, the logic to flip the flag is never called even if there is a value in rResponse variable. Infact, when methodName function is called, the code flow tries to check for the value of rResponse under if loop first and then calls the subscribe method at the end.

If you could please suggest the flow in which subscribe method works. Why is the if condition called before the actual subscribe method is called.

This is not a duplicate because I want to understand why the flow does not go to my if loop. There is nothing undefined. I am getting values from the service

DP3
  • 108
  • 6
  • 19
  • Possible duplicate of [Observable Undefined](https://stackoverflow.com/questions/41945817/observable-undefined) – jonrsharpe Nov 13 '17 at 22:50
  • The subscribe method is called immediately. The *callback you pass to it* is not, that's the whole point of asynchronous request handling. – jonrsharpe Nov 13 '17 at 22:50

1 Answers1

0

What I understand is you want to do some logic upon receiving value in rResponse.

As you might know that subscribe method call is asynchronous in nature i.e once request it made execution resumes to next lines.

So, as you have written if condition outside subscribe method, if condition gets executed immediately before completion of service call. Which results in empty response.

So, you need to place the if condition in the same block where you are assigning the this.rResponse = Response;

methodName (selectedData) {    
    this.service.Requests(Id).subscribe((Response => {
        this.rResponse = Response;
        if(this.rResponse) {
            // My logic to flip the flag
        }      
    }));        
}
Ibrokhim Kholmatov
  • 1,079
  • 2
  • 13
  • 16
Jatin Patel
  • 43
  • 1
  • 4