0

我的代码中有 3 个异步管道。

<div>{{formatedData$ | async}}</div>

<div>{{totalStatusData$ | async }}</div>

<div>{{totalPercentageData$ | async}}</div>

组件.ts

服务返回的实际数据如下

[{
        "name": "one",
        "steps": [{
                "id": 1,
                "passed": 1,
                "failed": 3
            },
            {
                "id": 2,
                "passed": 4,
                "failed": 0
            }
        ]
    },
    {
        "name": "two",
        "steps": [{
                "id":3 ,
                "passed": 10,
                "failed": 3
            },
            {
                "id": 4,
                "passed": 4,
                "failed": 8
            }
        ]
    }
]

this.formatedData$ = this.service.data().pipe(map(data) => {

return this.formatData1();

})

现在 this.formatedData$ 如下

[{
        "name": "one",
        "passed": 5,
        "failed": 3
    },
    {
        "name": "two",
        "passed": 14,
        "failed": 11
    }
]

this.totalStatusData$=this.formatedData$.pipe(map(data) => {
return formatData2(data)
});

现在 this.totalStatusData$ 如下

    {

        "passed": 19,
        "failed": 14
    }

$totalPercentageData = this.totalStatusData$.pipe(map(data) => {

return this.formatData3(data);

}) 

现在 $totalPercentageData 如下

{

        "passed": "57.57%",
        "failed": "42.42%"
    }

从实际服务数据开始,如何在不破坏 Observable 链的情况下将这些 Observable 链接到 One 而不是 One。

4

1 回答 1

0

如果我理解正确,您需要为 html 模板提供 3 种不同的数据转换,这些转换由对 async 服务的单次调用返回。

因此,如果是这种情况,您可以尝试以下策略,

// create an Observable that subscribes to the source, 
// in this case the service data call, and then shares this one subscription
// with the all other Observables that are created starting from it
this.data$ = this.service.data().pipe(
  share()
)

// then you create ab Observable that performs the first transformation
this.formatedData$ = this.data$.pipe(map(data) => {
  return this.formatData1();
})

// then you create an Observable that performs the second transformation 
// based on the results of the first transformation
this.totalStatusData$ = this.formatedData$.pipe(map(data) => {
   return formatData2(data)
});

// and so on

这里的想法是使用share运算符只调用一次this.service.data().

于 2020-03-19T21:56:03.380 回答