You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RxJS 7.x中无法覆盖@internal修饰的_subscribe方法的问题咨询

关于RxJS中_subscribe方法在v7.x版本的隐藏机制与替代方案

问题背景

在RxJS 6.x及更早版本中,RxJS的Subject.ts里的_subscribe方法被标记为@deprecated但仍可访问。我参与的项目中,曾通过override该方法来处理Subject被订阅时的逻辑。

升级到RxJS 7.x版本后,该方法被标记为protected和@internal,按TypeScript规则,继承Subject的类本应能访问protected方法,但现在无法覆盖,报错如下:

Error: src/app/common/util/updatable-subject.ts:42:11 - error TS4117: This member cannot have an 'override' modifier because it is not declared in the base class 'Subject<T>'. Did you mean 'subscribe'?

42  override _subscribe(subscriber: Subscriber<T>) {
             ~~~~~~~~~~


Error: src/app/common/util/updatable-subject.ts:43:30 - error TS2551: Property '_subscribe' does not exist on type 'Subject<T>'. Did you mean 'subscribe'?

43   const subscription = super._subscribe(subscriber);
                                ~~~~~~~~~~

  node_modules/rxjs/dist/types/internal/Observable.d.ts:50:5
    50     subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;
           ~~~~~~~~~
    'subscribe' is declared here.

我做了个最小测试示例,发现带有@internal的protected方法是可以正常覆盖的:

测试代码

app.ts

import express from 'express';
import {B} from './B';
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
  new B().subscribe();
});

app.listen(port, () => {
  return console.log(`Express is listening at http://localhost:${port}`);
});

A.ts

export class A {
    /**
     * @internal
     */
    protected _subscribe() {
        console.log("A");
    }
}

B.ts

import {A} from './A';

export class B extends A {
    override _subscribe() {
        super._subscribe();
        console.log("B");
    }

    subscribe() {
        this._subscribe();
    }
};

执行命令 npx tsc && node dist/app.js 并访问 http://localhost:3000/,日志输出:

Express is listening at http://localhost:3000
A
B

咨询问题

  • RxJS是如何通过@internal注解隐藏_subscribe方法的?
  • 是否仍有办法覆盖该方法?
  • 如果不能覆盖,有哪些其他方式可以知晓RxJS中该方法的调用时机及参数?

内容的提问来源于stack exchange,提问作者MetaColon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:12:13