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

Angular13中ngOnInit内.subscribe提示已弃用如何解决

问题原因

Angular 13 配套使用的 RxJS 7.x 版本中,支持将next、error、complete回调作为多个独立位置参数传入的subscribe方法重载,已经被官方标记为弃用,当前代码中依次传入三个独立函数的写法,就会触发弃用提示,对应位置会显示删除线。

修复方法

将分散传入的三个回调,统一封装为一个包含next、error、complete属性的Observer对象,作为subscribe方法的唯一入参传入即可,修复后的代码如下:

ngOnInit(): void {
  this.appSettingsService.getSettings()
    .subscribe({
      next: settings => this.settings = settings,
      error: () => null,
      complete: () => {
        this.defaultSidebarColor = this.settings.defaultSidebarColor;
        this.defaultBrandlogoColor =  this.settings.defaultBrandlogoColor;
      }
    });
}

这种对象传参的写法是RxJS 7之后推荐的标准写法,除了消除弃用提示外,还能避免参数顺序传错的问题,代码可读性更好。如果不需要处理某一类回调,直接在对象里省略对应属性即可,不需要强制传空函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 21:03:40