Typescript(原子编辑器中的tslint)给我一个打字稿错误,但我无法弄清楚如何设置正确的类型。
聊天组件:
private _chatObserver: Observable<firebase.database.DataSnapshot>
otherMethod () {
this._chatObserver = this._chat.observe(alarmId)
this._chatObserver.subscribe(
(messageSnap: firebase.database.DataSnapshot) => {
this.messages.push(messageSnap.val())
},
error => {throw error})
}
ionViewDidLeave() {
this._chatObserver.unsubscribe()
}
_chat提供者:
public observe (alarmId){
let messagesRef = this._ref.child(`alarms/${alarmId}/messages`)
const observable = Observable.create(observer => {
messagesRef.on('child_added',(messageSnap) => {
observer.next(messageSnap)
},
(error) => observer.error(error)
)
return () => {
messagesRef.off('value')
};
});
return observable
}
答案 0 :(得分:10)
Unsubscribe
是订阅本身的一种方法。因此,在顶部添加:
private _chatSubscription;
然后在otherMethod
:
this._chatSubscription = this._chatObserver.subscribe(...);
在你的破坏/离开/终止处理程序中:
this._chatSubscription.unsubscribe();
答案 1 :(得分:7)
试试这个
private _chatObserver: Observable<firebase.database.DataSnapshot>
private _subscription:Subscription
otherMethod () {
this._chatObserver = this._chat.observe(alarmId)
this._subscription=this._chatObserver.subscribe(
(messageSnap: firebase.database.DataSnapshot) => {
this.messages.push(messageSnap.val())
},
error => {throw error})
}
ionViewDidLeave() {
this._subscription.unsubscribe()
}