【问题标题】:distinctUntilChanged() on BehaviourSubject don't workdistinctUntilChanged() 一个 BehaviorSubject 不起作用
【发布时间】:2018-03-05 14:16:44
【问题描述】:

我的 package.json:

  • rxjs": "^5.5.6"
  • @angular: "6.0.0-beta.5

searchTextValueSubject 是一个 BehaviorSubject

import { debounceTime } from 'rxjs/operators';
import { distinctUntilChanged } from 'rxjs/operators';
import { pipe } from 'rxjs';

this.sharingVariableService
    .searchTextValueSubject
    .pipe(
        distinctUntilChanged((x, y) => {
            console.log(y.BarCodeS === x.BarCodeS);
            console.log(y.BarCodeS);
            console.log(x.BarCodeS);
            return y.BarCodeS === x.BarCodeS
        })
    )
    .subscribe((searchTextValue) => {
        this.searchTextValue = searchTextValue;
        this.getRessourceHardware(this.serverDataRessourceHardware._meta.max_results, this.searchTextValue);
    });

结果:

真,'d','d'

真的,'da','da'

预期:

假,'','d'

假,'d','da'

我可能不明白一些事情。你能指出我正确的方向吗?

【问题讨论】:

  • 嗨 Solinas,请注意我是如何重新格式化您的源代码的:以前很难理解,并且无法编译(它有一个额外的括号,请参阅编辑,但我冒昧地修复它,因为我将其视为复制/粘贴问题,而不是您的代码运行后的实际错误)。另请注意,虽然您(和我)想用不是操作员名称的“u”来写“行为”。
  • 非常感谢,我是堆栈溢出的新手,下次会更严格
  • 发布一个完整的最小示例来重现该问题。

标签: angular rxjs angular2-observables behaviorsubject


【解决方案1】:

看起来您可能正在向 searchTextValueSubject 发送变异值。

确保您的代码没有在做这样的事情...

let value = {BarCodeS: 'd'}
this.sharingVariableService.searchTextValueSubject.next(value);

value.BarCodeS = 'da'; // wrong!
this.sharingVariableService.searchTextValueSubject.next(value);

正确的做法是这样的:

const value0 = {BarCodeS: 'd'}
this.sharingVariableService.searchTextValueSubject.next(value0);

const value1 = {...value0, BarCodeS: 'da'}; // right
this.sharingVariableService.searchTextValueSubject.next(value1);

另请注意,在 first 发射时永远不会调用 distinctUntilChanged 比较器函数(第一个发射必然是不同的)

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 2018-08-31
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多