angular - 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中获取服务端返回的数据?
解决方案
记录的对象绝对看起来像订阅。那就是:如果你这样做了
const mySubscription = this.http.post(...someArgs).subscribe();
console.log(mySubscription);
你会得到一个像你粘贴的对象。
数据可用于订阅内的消费:
this.http.post(...someArgs).subscribe(res => {
this.someVariable = res;
console.log(res);
});
推荐阅读
- python - 跨 NumPy 数组矢量化字符串格式
- java - Raw Spring 5 和 Commons FileUpload 不起作用
- python - 如果另一行中已存在相同值,则在数据框列中填充空值
- c# - 我在 C# 中的 Mandelbrot 素描程序不工作
- drupal-8 - Drupal 8 得到空的 $_GET 变量
- json - 使用可变字段名称和值类型转换 JSON 结果
- api - 遍历 PowerShell 对象中的每一行并提取变量
- python - “int”对象没有属性“ljust”
- visual-studio-code - Intellij 喜欢 vs 代码中的内联参数提示
- php - 选择当前(周或任何给定周)记录,不包括周末和假期