【发布时间】:2016-12-14 04:36:11
【问题描述】:
我一直在尝试使用 TypeScript 在 Angular 2 组件中实现新的 rxjs Observable。我创建了一个服务,MyService,它在其中一个方法中返回一个 observable,例如,
export class MyService {
getMyObs(){
return new Observable(observer => {
observer.next(42);
});
}
}
然后在我的 Angular 2 组件中,我在 OnInit 中订阅这个 observable,例如,
export class MyComponent implements OnInit {
obs: any;
constructor(private myService: MyService){};
ngOnInit {
this.obs = myService.getMyObs().subscribe(data => {
// Do stuff here...
});
}
}
RxJs documentation 谈论取消订阅你的 observable 以便你的 observable 知道不再向你的观察者发送消息。因此,我认为当我的组件被销毁时,我应该取消订阅 observable,例如
export class MyComponent implements OnInit, OnDestroy {
obs: any;
constructor(private myService: MyService){};
ngOnInit {
this.obs = myService.getMyObs().subscribe(data => {
// Do stuff here...
});
}
ngOnDestroy {
this.obs.unsubscribe();
}
}
虽然这对我来说很有意义,但 typescript 编译器会抛出(实际上是应用程序会抛出)说没有 unsubscribe 方法。类型定义文件中似乎没有描述这种方法。如何使用 TypeScript 正确取消订阅 observable?
【问题讨论】:
标签: angularjs angular typescript rxjs