0
votes

I've subscribed to an observable as follows

onClickSubmit(data) {
  this.http.post("http://localhost:8080/demo/add", data).subscribe( (ob)=>(console.log(ob)));

}

This method gets called on a form submission..From what I understand server responds to this subscription by invoking the subscribe method and pass an observable into ob parameter. My server is returning a list of objects as response

@PostMapping(path="/add") 
  public  @ResponseBody Iterable<Fruits> addNewUser(@RequestBody Fruits fruits) {
      fruitsRepository.save(fruits);
      return fruitsRepository.findAll();
}

Even though my controller is returning a list of objects I'm not able to access it from the observable, When I log the observable I don't get the list of objects returned instead log shows an object as follows

{
  "closed": true,
  "_parentOrParents": null,
  "_subscriptions": null,
  "syncErrorValue": null,
  "syncErrorThrown": false,
  "syncErrorThrowable": true,
  "isStopped": true,
  "destination": {
    "closed": true,
    "_parentOrParents": null,
    "_subscriptions": null,
    "syncErrorValue": null,
    "syncErrorThrown": false,
    "syncErrorThrowable": false,
    "isStopped": true,
    "destination": {
      "closed": true
    },
    "_parentSubscriber": null,
    "_context": null
  }
}

This object does not contain result returned by the server,How to get the data returned by the server from the observable?

3

3 Answers

2
votes

The object that is logged definitely looks like a subscription. That is: if you did

const mySubscription = this.http.post(...someArgs).subscribe();
console.log(mySubscription);

You'd get an object like the one you pasted.

The data is available for consumption inside the subscription:

this.http.post(...someArgs).subscribe(res => {
    this.someVariable = res;
    console.log(res);
});
1
votes

You can create a variable fooData and store value of response. Then you can use your data in your component:

fooData: any;

onClickSubmit(data) {
  this.http.post("http://localhost:8080/demo/add", data).subscribe( (ob)=> {
       this.fooData = ob;
       console.log(this.fooData);
      });    
}
0
votes

Actually I think you need to do something like this :

onClickSubmit(data): Observable<any> {
  return this.http.post<any>("http://localhost:8080/demo/add", data);
}

You have to subscribe when you call it like :

this.service.onClickSubmit(data).subscribe(console.log);