在回调函数中使用箭头函数来确保this指向正确。例如:
export class MyService {
private mySubject = new BehaviorSubject(null);
constructor() { }
myFunc() {
this.mySubject.subscribe({
next: (value) => {
console.log(value);
console.log(this); // this指向MyService实例
}
});
}
}
使用箭头函数来定义回调函数,可以将当前作用域中的this指向正确的对象,避免出现该问题。