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
相关产品推荐
相关产品推荐

