0

I have a very simple service.ts file. I can console log the responeDataSent object.

  CallFunction() {
    this.http
      .post<{ someObject: any }>(
        'http://localhost:3000/apicall1',
        InputData
      )
      .subscribe(responseData => {
        this.responeDataSent = responseData;
        return this.responeDataSent;
      });
  }

In my component.ts file, how can I read this response. Please help.

  private context: any;
  ngOnInit() {
    this.context = this.service.CallFunction();
    console.log(this.context);  // comes undefined.

  }
user2281858
  • 1,957
  • 10
  • 41
  • 82
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ConnorsFan Mar 25 '19 at 21:48
  • remove the`subscribe` from `CallFunction()` and subscribe inside the `ngOnInit()` – Jason White Mar 25 '19 at 21:50
  • The service method `CallFunction` should return the observable. You should then subscribe to it in the component method, and do the processing in the callback. – ConnorsFan Mar 25 '19 at 21:50

2 Answers2

1

I guess a better way to deal with this scenario is that your service function should return an Observable first:

CallFunction(): Observable<any> {
  this.http.post<{ someObject: any }>(
    'http://localhost:3000/apicall1',
    InputData
  );
}

Then in component.ts you can subscribe and the code can handle the response:

ngOnInit() {
  this.service.CallFunction().subscribe(responseData => {
    console.log('response', responseData);
  });
}

Read further about Observables: Observables

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

This is my way to handle HttpClient request. Return http post/get after call in function.

CallFunction(InputData) {
        return this.http
          .post<{ someObject: any }>(
            'http://localhost:3000/apicall1',
            InputData
          );
      }

And use subscribe after call function.

private context: any;
  ngOnInit() {
this.service.CallFunction().subscribe(responseData => {
      this.context =  = responseData;
      // handle your data here
      console.log(this.context);  // comes undefined.
 } 
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62