首页 > 解决方案 > Angular - 从服务 API 调用中分配多个 Observable 数组

问题描述

我有一个调用 API 来返回 Observable 的服务Observable<MeasuringPoint[]>

我希望能够为该服务的结果订阅多个变量。每个变量 MeasuringPoints$、MeasuringPointsViewed$、LatestReadings$ 都需要相同的数据,但会以不同的方式解析它。他们还需要彼此不了解。

关于最好的方法的任何想法?

标签: angularrxjs

解决方案


我想到了这样的事情:

export class ConsumerComponent implements OnInit {
    mesuringPoint$: Observable<MesurePointModel>;
    mesuringPointView$: Observable<MesurePointModelView>;
    latestReadings$: Observable<number>;

    constructor(private service: DataStoreService) {
        this.mesuringPoint$ = this.service.getData().pipe(// rxjs operators);
        this.mesuringPointView$ = this.service.getData().pipe(// rxjs operators );
        this.latestReadings$ = this.service.getData().pipe( // rxjs operators );


    ngOnInit() {
       // Subscribe here or anywhere else to your observables
       this.latestReadings$.subscribe(latestReadings => // number of latest readings)
    }


}

重要的部分是使用 RXJS 来转换或组合运算符,这样您就可以创建新的 observable,将您的服务的 observable 作为输入,然后通过管道将其创建为您自己的。

RXJS 运算符


推荐阅读