【问题标题】:Angular: Editing a specific element in a behaviour subject of type <T[]>Angular:编辑 <T[]> 类型的行为主题中的特定元素
【发布时间】:2023-03-09 13:11:01
【问题描述】:

我有一个显示序列列表的 html 表格,我正在使用序列 [] 类型的 BehaviourSubject 填充此页面

   private sequencesSubject = new BehaviorSubject<Sequence[]>([]);

   findSequences(pageIndex: number, pageSize: number, rrc: string): Observable<PaginatedResult> {

        return this.http.get<PaginatedResult>('https://bgpie.net/api/rrc/' + rrc + '/sequence', {
            params: new HttpParams()
                .set('page', pageIndex.toString())
                .set('limit', pageSize.toString())
        });
    }

   loadSequences(pageIndex: number,
                  pageSize: number,
                  rrc: string) {

        this.loadingSubject.next(true);

        this.sequencesService.findSequences(pageIndex, pageSize, rrc).pipe(
                /*catchError(() => of([]))*/
                finalize(() => this.loadingSubject.next(false)),
                tap(x => this.length.next(x.total))
            )
            .subscribe((sequences: PaginatedResult) => this.sequencesSubject.next(sequences.items));
    }

这些是 PaginatedResult 和 Sequence 的接口

export interface PaginatedResult{
  readonly items: Sequence[];
  readonly total: number;
}

我的表在每一行中都包含一个序列,这些行是可扩展的。当行展开时(当我单击它们时),它们会显示更多涉及该特定序列的数据,我希望仅在单击行时才填充此数据。我正在尝试创建一种方法来编辑我的序列主题,将我点击的序列替换为我从 http 请求中获得的序列

getSequence(id: string): Observable<Sequence> {
      return this.http.get<Sequence>('https://bgpie.net/api/sequence/' + id);
    }

我不知道如何访问 sequenceSubject 的特定元素,将其替换为我从 getSequence 获得的元素。

【问题讨论】:

    标签: angular http rxjs behaviorsubject


    【解决方案1】:

    从您的BehaviorSubject 中检索最新值,将匹配id 的序列替换为您从网络调用中检索的值,然后发出新数组。

    class SequencesList {
      private sequencesSubject = new BehaviorSubject<Sequence[]>([]);
    
      constructor(private http: Http, private sequencesService: SequencesService) {
        sequencesService.findSequences().subscribe(sequences =>
          this.sequencesSubject.next(sequences);
        );
      }
    
      async onSequenceClick(event: any) {
        const id = event.target.id;
        const sequenceWithDetails = this.http.get<Sequence>('/api/sequence/' + id);
        const sequences = this.sequencesSubject.getValue();
        const sequenceIndex = sequences.findIndex(seq => seq.id === id);
        sequences[sequenceIndex] = sequenceWithDetails;
        this.sequencesSubject.next(sequences);
      }
    }
    

    【讨论】:

    • 真的没有办法用 BehaviorSubject 做到这一点吗?我的整个项目都是以此为基础的。
    • 如果您愿意,可以使用主题发出新的sequences。更新了我的答案以反映这种方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2010-12-31
    • 2010-12-05
    • 2020-03-03
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多