You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular父子及兄弟组件间共享过滤后的对象数组

解决方案:Angular中共享过滤后数组的几种最佳实践

1. 用单例服务共享状态(最推荐)

  • 创建一个全局单例服务,比如LocationFilterService,专门维护过滤后的地点数组状态:
    // location-filter.service.ts
    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { Location } from './location.model';
    
    @Injectable({ providedIn: 'root' })
    export class LocationFilterService {
      private filteredLocations$ = new BehaviorSubject<Location[]>([]);
      public readonly filteredLocations = this.filteredLocations$.asObservable();
    
      updateFilteredList(locations: Location[]): void {
        this.filteredLocations$.next(locations);
      }
    }
    
  • 在Filter Component(父组件)中,完成过滤逻辑后调用服务的更新方法:
    // filter.component.ts
    constructor(private filterService: LocationFilterService) {}
    
    onFilter(): void {
      const filteredList = this.locations.filter(/* 你的过滤逻辑 */);
      this.filterService.updateFilteredList(filteredList);
    }
    
  • 子组件和兄弟组件只需订阅服务中的Observable,就能实时获取更新后的数组:
    // child/sibling.component.ts
    displayedLocations: Location[] = [];
    
    constructor(private filterService: LocationFilterService) {}
    
    ngOnInit(): void {
      this.filterService.filteredLocations.subscribe(list => {
        this.displayedLocations = list;
      });
    }
    

2. 通过父组件中转(适合层级简单的场景)

  • 如果所有需要共享数据的组件都有共同的父组件,直接在父组件中维护过滤后的数组:
    • 父组件存储filteredLocations变量,过滤完成后更新它
    • 子组件通过@Input() filteredLocations: Location[]接收数据,自动同步更新
    • 兄弟组件若需触发过滤,通过@Output()向父组件传递过滤条件,父组件重新计算后更新数组

3. 性能优化提示:避免用管道做过滤

  • 你当前用管道实现过滤,虽然能运行,但Angular纯管道会在每次变更检测时重新执行,数据量大时会拖慢性能。建议把过滤逻辑移到组件或服务中,只在过滤条件变化时重新计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:10:20