我一直在尝试使用TypeScript在Angular 2组件中实现一个新的rxjs可观察
。我创建了一个服务MyService
,它在其方法之一中返回一个可观察对象,例如,
export class MyService {
getMyObs(){
return new Observable(observer => {
observer.next(42);
});
}
}
然后在我的Angular 2组件中,我在OnInit中订阅了这个可观察的对象,例如,
export class MyComponent implements OnInit {
obs: any;
constructor(private myService: MyService){};
ngOnInit {
this.obs = myService.getMyObs().subscribe(data => {
// Do stuff here...
});
}
}
RxJs留档讨论了取消订阅你的可观察对象,这样你的可观察对象就知道不再向你的观察者发送消息。因此,我想当我的组件被销毁时,我应该取消订阅可观察对象,类似
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编译器抛出(实际上是应用程序抛出)说没有取消订阅
方法。类型定义文件中似乎没有描述这样的方法。如何使用TypeScript正确取消订阅可观察对象?
您需要将取消订阅方法添加到您的可观察
。,处置可观察执行
return new Observable(observer => {
observer.next(42);
return () => {
console.log('unsubscribe')
}
});
您可以在Rxjs模块的Subscription. d.ts
(classSubscription
)中找到取消订阅
方法的定义。
事实上,您取消订阅的是订阅,而不是可观察订阅。
首先创建订阅,如下所示。
private obs: Subscription = new Subscription();
然后分配给可观察的。
this.obs = myService.getMyObs().subscribe(data => {
if(data !== null){
this.obs.unsubscribe()
}
});