Angular从v8升级至v12后subscribe回调中this指向失效的最优解决办法
最优解决方案
你遇到的this指向问题是因为改为Observer对象写法时,使用了普通函数声明next、error回调,普通函数的this会在调用时绑定到执行上下文,而非外层类实例。最简单的解决方式是直接将Observer对象的回调属性改为箭头函数,箭头函数会继承外层作用域的this指向,无需额外存储this引用,这也是目前社区的通用标准写法:
this._trialService.currentTrial().subscribe({ next: (trial) => { this.trial = trial; this.loadVisitDetails(); }, error: (error) => { this._alertService.showWarningAlert(error.error.title); } });
原有的多参数回调写法被弃用是RxJS后续版本的统一规范要求,调整为Observer对象写法时不需要改变箭头函数的使用习惯即可适配。
其他可选方案
如果回调逻辑较多需要抽离为类的独立成员方法,可以使用Function.prototype.bind手动绑定this指向:
// 订阅逻辑 this._trialService.currentTrial().subscribe({ next: this.handleTrialNext.bind(this), error: this.handleTrialError.bind(this) }); // 类中抽离的回调方法 private handleTrialNext(trial: Trial) { this.trial = trial; this.loadVisitDetails(); } private handleTrialError(error: HttpErrorResponse) { this._alertService.showWarningAlert(error.error.title); }
你提到的const self = this是ES6箭头函数普及前的旧解决方案,现在完全不需要使用,可读性和可维护性都不如上述两种方案。
内容的提问来源于stack exchange,提问作者SheppardDigital
相关产品推荐
相关产品推荐

