我有一个可观察的流,设置如下。我有一个每两秒轮询一次的时间间隔。然后,我将其切换为两个相关的 API 调用(此处用“of”进行模拟)。之后,我想使用distinctUntilChanged来确保最终对象是不同的。唯一的问题是,distinctUntilChanged 不会触发。
我假设它与我们正在创建新流因此从不收集两个对象进行比较这一事实有关,但我不完全理解。
interval(2000).pipe(
switchMap(() => loadData()),
)
.subscribe(res => console.log(res)); // { name: 'test' } is printed every two seconds
function loadData() {
return of('API call').pipe(
mergeMap(numb => of({ name: 'test' })),
distinctUntilChanged((prev, cur) => {
console.log('CompareFn'); // This will never fire.
return JSON.stringify(prev) === JSON.stringify(cur)})
);
}
Run Code Online (Sandbox Code Playgroud)
Stackblitz:https://stackblitz.com/edit/rxjs-ko6k3c?devtoolsheight =60
在这种情况下,我希望只有一个从下一个处理程序打印的值,因为distinctUntilChanged应该停止第一个处理程序之后的所有值。
希望能解释一下为什么这不能像我预期的那样工作。
背景:单击按钮后,我的主页会打开项目中另一个模块的外部窗口(相同来源)。我还设置了一个 BroadcastChannel 以便这两个窗口现在可以通信。现在,如果此窗口已打开并且用户再次单击触发按钮,我想将此信息传达给窗口:
onAddNewFieldClick() {
if (this.window === null) {
this.window = window.open(window.location.origin + '/wizard', 'Field Wizard', 'resizable,scrollbar');
this.channel = new BroadcastChannel('edit-spec-wizard-channel');
} else {
this.channel.postMessage(1);
}
}
Run Code Online (Sandbox Code Playgroud)
新窗口侦听此通道并将消息数据附加到 ngFor 中使用的数组。为了更加安全。每次推送新值以导致重新绑定时,我都会继续创建一个全新的数组。这是在新窗口中为组件供电的逻辑。
export class EntryComponent implements OnInit, OnDestroy {
newFieldChannel: BroadcastChannel;
newFields: number[] = [];
constructor() { }
ngOnInit() {
this.newFieldChannel = new BroadcastChannel('edit-spec-wizard-channel');
this.newFieldChannel.onmessage = this.newFieldChannelOnMessage.bind(this);
this.newFields.push(1);
}
func() {
this.newFields.push(1);
this.newFields = this.newFields.slice();
}
private newFieldChannelOnMessage(event: MessageEvent) {
this.newFields.push(event.data as number);
this.newFields = this.newFields.slice();
}
ngOnDestroy() {
this.newFieldChannel.close();
} …Run Code Online (Sandbox Code Playgroud)