Angular中subscribe作用域内this上下文缺失DataGrid实例的解决问询
解决Angular订阅回调中无法获取组件实例的问题
嘿,这个问题我太熟了!你遇到的要么是this上下文绑定的坑,要么是组件初始化时机不对,给你几个实用的解决办法:
先确认箭头函数的正确使用
你当前代码里用了箭头函数number => {...},按道理箭头函数会自动继承外部的this(也就是你的product组件实例),如果还是拿不到gridProduct这些,先检查是不是不小心写成了普通函数function(number) {...}——普通函数的this会指向订阅的上下文,而不是组件本身。如果确认是箭头函数,接着看下面的方案。提前保存组件上下文到变量(稳得一批的老方法)
把组件的this提前存到一个变量里,比如that,然后在回调里用这个变量,完全绕开this绑定的问题:constructor(.........) { const that = this; // 保存组件的this引用 this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => { that.gridProduct.instance.refresh(); that.gridPrice.instance.refresh(); }); }用
bind()强制绑定上下文
如果你偏好使用普通函数作为回调,可以用bind()把组件的this强制绑定进去:constructor(.........) { this.service.refreshNumberOfAllPriceByCurrency.subscribe(function(number) { this.gridProduct.instance.refresh(); this.gridPrice.instance.refresh(); }.bind(this)); // 绑定组件的this到回调函数 }检查组件初始化时机(最容易忽略的点)
要是你是通过@ViewChild获取的gridProduct和gridPrice实例,那在constructor里订阅的时候,这些实例还没初始化完成!因为@ViewChild的赋值是在ngAfterViewInit钩子之后才完成的。这种情况下,你得把订阅逻辑移到ngAfterViewInit里:import { AfterViewInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; export class ProductComponent implements AfterViewInit { @ViewChild('gridProduct') gridProduct: any; // 假设你用@ViewChild获取实例 @ViewChild('gridPrice') gridPrice: any; private priceRefreshSub: Subscription; constructor(private service: YourService) {} ngAfterViewInit(): void { // 这里gridProduct和gridPrice已经完成初始化了 this.priceRefreshSub = this.service.refreshNumberOfAllPriceByCurrency.subscribe(number => { this.gridProduct.instance.refresh(); this.gridPrice.instance.refresh(); }); } }额外提醒:别忘取消订阅避免内存泄漏
最后说个重要的点,Angular里订阅后一定要记得取消订阅,不然会导致内存泄漏。你可以在ngOnDestroy钩子中完成这个操作:ngOnDestroy(): void { if (this.priceRefreshSub) { this.priceRefreshSub.unsubscribe(); } }
内容的提问来源于stack exchange,提问作者Erkan Yanbul
相关产品推荐
相关产品推荐

