You need to enable JavaScript to run this app. 如何基于observerB$的收藏ID为observerA$的对应条目添加favorite布尔标记
优惠活动
大模型
产品
解决方案
定价
更多

如何基于observerB$的收藏ID为observerA$的对应条目添加favorite布尔标记

实现方案

核心逻辑通过RxJS组合操作符封装可复用的带收藏标记的可观察对象,无需在组件内手动维护数组,任意数据源更新都会自动同步标记状态。

1. 导入依赖

import { combineLatest, map, shareReplay } from 'rxjs';

2. 定义公共类型(可放到全局类型文件复用)

export interface BusinessItem {
  title: string;
  id: number;
  page: string;
  subcategory: string;
  favorite?: boolean;
}

3. 封装组合可观察对象(可放到共享服务/公共工具文件中多组件复用)

export const itemListWithFavorite$ = combineLatest([
  observerA$,
  // 先将收藏列表转换为id Set,实现O(1)效率的存在性判断
  observerB$.pipe(
    map(favoriteList => new Set(favoriteList.map(item => item.id)))
  )
]).pipe(
  map(([businessList, favoriteIdSet]) => 
    businessList.map(item => ({
      ...item,
      favorite: favoriteIdSet.has(item.id)
    })) as BusinessItem[]
  ),
  // 可选优化:加shareReplay缓存最近一次计算结果,多组件订阅不会重复执行标记逻辑
  shareReplay(1)
);

4. 组件内直接使用

模板中直接通过async管道订阅即可,无需编写额外TS逻辑维护数组:

<div *ngFor="let item of itemListWithFavorite$ | async">
  <p>{{ item.title }}</p>
  <span *ngIf="item.favorite">已收藏</span>
</div>

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 21:45:02