首页 > 解决方案 > Angular:如何从可观察对象中获取内容?

问题描述

我订阅了一个 observable 如下

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

}

此方法在表单提交时被调用。据我所知,服务器通过调用 subscribe 方法响应此订阅并将 observable 传递给 ob 参数。我的服务器正在返回一个对象列表作为响应

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

即使我的控制器返回一个对象列表,我也无法从可观察对象访问它,当我记录可观察对象时,我没有得到返回的对象列表,而是日志显示如下对象

{
  "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
  }
}

该对象不包含服务端返回的结果,如何从observable中获取服务端返回的数据?

标签: angulartypescript

解决方案


记录的对象绝对看起来像订阅。那就是:如果你这样做了

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

你会得到一个像你粘贴的对象。

数据可用于订阅内的消费:

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

推荐阅读