我有以下代码,我想在其中覆盖next
有一些自定义逻辑。这种方式行不通,但只有在以下情况下才有效next
是一个带有箭头函数的属性。其背后的原因是什么?
export class Store<T> extends ReplaySubject<T | undefined> {
next(value?: T) {
console.log("do something in my code");
super.next(value);
}
}
export class Store<T> extends ReplaySubject<T | undefined> {
next = (value?: T) => {
console.log("do something in my code");
super.next(value);
};
}
https://stackblitz.com/edit/typescript-override-subject-next https://stackblitz.com/edit/typescript-override-subject-next
今天,我也结束了ReplaySubject
以获得最后的值。为此,我提出了一个公关-https://github.com/ReactiveX/rxjs/pull/6652/files https://github.com/ReactiveX/rxjs/pull/6652/files但为了同时解决我的项目,我扩展了ReplaySubject
同样的事情也发生在我身上;这next
没有被覆盖。
我快把自己逼疯了,为什么会发生这种事。我跳进源代码,发现在 RxJS 6.x 版本中,next
方法 id 被函数赋值覆盖 -https://github.com/ReactiveX/rxjs/blob/6.6.7/src/internal/ReplaySubject.ts#L31 https://github.com/ReactiveX/rxjs/blob/6.6.7/src/internal/ReplaySubject.ts#L31这就是为什么它没有被覆盖。
根据同一文件的历史记录,我发现这种行为在 v7.x 中发生了变化(7.0.0-beta.6 https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#700-beta6-2020-09-23具体来说)在此承诺中-https://github.com/ReactiveX/rxjs/commit/f1dcada1e1838ffb01cd0dac60340c6fa068f3cf#diff-a287f66fc20bf26caa2f42935756aa6a094f400e91d6b4a388aee4e4e11675c4 https://github.com/ReactiveX/rxjs/commit/f1dcada1e1838ffb01cd0dac60340c6fa068f3cf#diff-a287f66fc20bf26caa2f42935756aa6a094f400e91d6b4a388aee4e4e11675c4.
所以你必须升级到 RxJS 7.x 版本才能使其工作。
如果您无法升级到 7.x 版本 - 这是解决方法 -
export class Store<T> extends ReplaySubject<T | undefined> {
private originalNext: any;
constructor(bufferSize: number, windowTime: number) {
super(bufferSize, windowTime);
this.originalNext = super.next;
this.next = this.emit;
}
private emit(value?: T): void {
console.log("do something in my code");
super.next(value);
};
}
Cheers!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)