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.

  }
3
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Mar 25, 2019 at 21:48
  • remove thesubscribe from CallFunction() and subscribe inside the ngOnInit() Commented Mar 25, 2019 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. Commented Mar 25, 2019 at 21:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.
 } 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.