首页 > 解决方案 > 如何给物体补水?

问题描述

我已经开始研究一个小的 Angular 问题,虽然我一直在搜索教程和文档,但我还没有找到解决这个问题的好方法。我可以很容易地在 Angular 之外解决它,但我希望有人可以稍微推动一下 Angular 的路线吗?

本质上,我从不同的源文件中提取了 2 个对象:

福斯

{
   id: 1,
   name: "Foo1",
   bars: [ 1, 2, 3 ]
}

酒吧

 {
    id: 1,
    name: "Bar1"
 }

我正在尝试在单独的页面上显示每个列表。但我需要列出页面BarsFoos.html的名称和页面上链接的Foos名称Bars.html

我想有两种可能的解决方案:

我的 Foo 类型看起来像:

{
    id: number;
    name: string;
    bars: Bar[];
}

在非 Angular 世界中,我相信正确的方法是在服务中(或者更有可能通过某种控制器)。我一直在尝试在服务级别实现这一点,但我正在努力弄清楚如何在跨 2 个请求的情况下做到这一点?特别是考虑到通常 Angular 会HttpClient自动转换为Foo.

我在这里使用错误的方法吗?我在 Angular2+ 中看不到任何提及,Controllers所以我在这里遗漏了什么吗?

标签: angularrxjs

解决方案


我认为您认为这不是“角度”问题的直觉是正确的。这些天来,我会说这更像是一个 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 等,但一般要点是我上面所说的。


推荐阅读