Ionic 类型'Observable '上不存在属性'unsubscribe'< DataSnapshot>

7gs2gvoe  于 2022-12-09  发布在  Ionic
关注(0)|答案(2)|浏览(161)

Typescript(atom编辑器中的tslint)正在给我一个typescript错误,但我不能想出如何设置正确的类型。
错误消息:

聊天组件:

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() 
    }

聊天提供程序(_C):

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
  }
blpfk2vs

blpfk2vs1#

Unsubscribe是订阅本身的方法。因此,请在顶部添加:

private _chatSubscription;

然后在您的otherMethod

this._chatSubscription = this._chatObserver.subscribe(...);

在销毁/离开/终止处理程序中:

this._chatSubscription.unsubscribe();
p5cysglq

p5cysglq2#

订阅的可观察对象将返回具有unsubscribe()方法的订阅示例

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() 
}

相关问题