【问题标题】:Property 'unsubscribe' does not exist on type 'Observable<DataSnapshot>'类型“Observable<DataSnapshot>”上不存在属性“取消订阅”
【发布时间】:2018-04-05 00:35:01
【问题描述】:

Typescript(原子编辑器中的 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() 
    }

_聊天提供者:

  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
  }

【问题讨论】:

  • unsubscribe 应该在 Subscription 上调用 - 而不是在 Observable 上调用。您对subscribe 的调用将返回Subscription

标签: angular typescript ionic-framework rxjs tslint


【解决方案1】:

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

private _chatSubscription;

然后在你的otherMethod:

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

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

this._chatSubscription.unsubscribe();

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2018-02-01
      • 2019-01-03
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      相关资源
      最近更新 更多