【问题标题】:How to properly chain Dependent Async Pipes in Angular如何在 Angular 中正确链接依赖的异步管道
【发布时间】:2020-03-20 05:56:03
【问题描述】:

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

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

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

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

component.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。

【问题讨论】:

    标签: angular rxjs observable async-pipe


    【解决方案1】:

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

    所以,如果是这种情况,可以试试下面的策略,

    // 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() 包装的远程API。

    【讨论】:

    • 但在这种情况下,它会破坏可观察链,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多