angular - 如何给物体补水?
问题描述
我已经开始研究一个小的 Angular 问题,虽然我一直在搜索教程和文档,但我还没有找到解决这个问题的好方法。我可以很容易地在 Angular 之外解决它,但我希望有人可以稍微推动一下 Angular 的路线吗?
本质上,我从不同的源文件中提取了 2 个对象:
福斯
{
id: 1,
name: "Foo1",
bars: [ 1, 2, 3 ]
}
酒吧
{
id: 1,
name: "Bar1"
}
我正在尝试在单独的页面上显示每个列表。但我需要列出页面Bars
中Foos.html
的名称和页面上链接的Foos
名称Bars.html
。
我想有两种可能的解决方案:
- 在 UI 中查找
- 在服务中补水
我的 Foo 类型看起来像:
{
id: number;
name: string;
bars: Bar[];
}
在非 Angular 世界中,我相信正确的方法是在服务中(或者更有可能通过某种控制器)。我一直在尝试在服务级别实现这一点,但我正在努力弄清楚如何在跨 2 个请求的情况下做到这一点?特别是考虑到通常 Angular 会HttpClient
自动转换为Foo
.
我在这里使用错误的方法吗?我在 Angular2+ 中看不到任何提及,Controllers
所以我在这里遗漏了什么吗?
解决方案
我认为您认为这不是“角度”问题的直觉是正确的。这些天来,我会说这更像是一个 RxJS 问题。您需要发出两个请求,并将来自第二个有效负载的数据放入第一个请求中,然后返回该组合有效负载。
在 RxJS 的说法中,归结为这样的事情:
import { HttpClient } ...
const stream_1$ = this.http.get ( 'url_1' );
const stream_2$ = this.http.get ( 'url_2' );
stream_1$.pipe (
switchMap ( x => {
// x will be the result of the first stream,
// you are literally switching to the second stream
return stream_2$.pipe (
map ( y => {
// y will be the result of the second stream.
// So you want to combine x, and y.
// Do your hydration here
return ( { some transformed object using x + y data } );
} )
} )
).subscribe ( x => // result will be that combined object )
这就是你现在做这类事情的方式,一个非常标准的 RxJS 模式。您可能想研究不同的运算符,mergeMap 等,但一般要点是我上面所说的。
推荐阅读
- postgresql - 从 Postgres 到 Hive/HDFS 的每日数据归档
- jmeter - 如何在 PKS 上安装 apache Jmeter (pivotal-container-service)
- python - 我怎样才能随机获取摩尔斯电码输入和输出意大利语单词?
- javascript - 如何将数据从剪贴板粘贴到多个输入字段?
- c++ - 双线程二叉搜索树 - 保存父节点和祖父节点以设置线程
- python-3.x - 打印账单
- c# - 使用同一个类存储函数多次运行的数据
- php - Lavarel - 关系错误:调用模型 [App\Nota] 上的未定义关系 [nota]
- node.js - 如何让会话在跨域中正常运行?
- android - 需要检测 Home Key 以显示对话框