在数组类型的 RxJS 主题上调用 .next() 不会通知观察者

kri*_*tof 0 subject observers rxjs subject-observer angular

我正在构建一个过滤器,您可以在其中按类别过滤,您可以通过单击类别名称旁边的复选框来选择一个类别。

所以我有一个filterComponent,它包含它自己的过滤器,然后是一个filterService,它有一个类别属性Subject<Array<ICategory>>,这个属性用于将数据传递到productsComponent我订阅类别属性的位置。

当我想使用此模式传递一个简单的字符串时,此逻辑有效,但当我想传递对象数组时,它似乎不起作用。

在我的 filters.component.html 文件中,当复选框值发生变化时,我正在调用一个方法:

<li *ngFor="let category of categories">
        <mat-checkbox (change)="addOrRemoveCategory(category)" [(ngModel)]="category.isChecked">
                {{'category.' + category.Name | translate}}
        </mat-checkbox>
</li>
Run Code Online (Sandbox Code Playgroud)

addOrRemoveCategory 方法实现如下所示:

private addOrRemoveCategory(category: ICategory): void {
    if (!this.chosenCategories.includes(category)) {
        this.add(category);
    } else {
        this.remove(category);
    }
    this.filterService.categories.next(this.chosenCategories);
}
Run Code Online (Sandbox Code Playgroud)

所以无论一个类别发生了什么,被添加或删除,(我在内部修改了selectedCategories数组,我用它的值调用 .next() ),我用更新的数组调用 .next() 。

问题是,当selectedCategories数组为空时,我推送到它,并用它调用 .next() 时,我正确地获取了订阅者函数中的值,但是如果再次执行此操作,并且我有一个2 个元素数组,我调用 .next(this.chosenCategories),我的订阅者方法没有收到通知。

但是,一旦我使用空数组调用 .next() ,我的订阅者方法就会再次收到通知(因为我已经删除了之前选择的所有类别)。

订阅者方法:

this.categoriesChangeSubscription = this.filterService.categories
            .pipe(
                debounceTime(500),
                distinctUntilChanged()
            )
            .subscribe((categories: Array<ICategory>) => {
                this.categories = categories.map(category => category.Name);
                this.loadData();
            });
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?我是否必须以不同于字符串的方式处理数组?

结论:如果我用作 .next() 参数的数组发生变化:

  • 从长度 0 到 1,我收到通知,
  • 如果长度从 1 变为 0,我会收到通知,
  • 但如果长度从 1 变为 2,或 5-6,或 8 变为 7,我不会收到通知

Ant*_*sak 6

我的猜测是 distinctUntilChanged() 过滤掉您更改的数组,因为从技术上讲它与以前是相同的对象。

您可以通过克隆数组来解决它:

this.filterService.categories.next([...this.chosenCategories]);
Run Code Online (Sandbox Code Playgroud)

类似问题更多解决方案。