【问题标题】:how to re-subscribe after unsubscribing an Observable取消订阅 Observable 后如何重新订阅
【发布时间】:2020-06-28 09:58:52
【问题描述】:

我创建了一个 socketService,我在其中不断获取数据更新,并且在我的组件上我订阅了我的 getUpdates Observable。

我必须取消订阅 stop 操作并在 start 操作按钮上再次订阅。

取消订阅在 stop 操作上效果很好,但之后它不再订阅 start 操作按钮。

这是我的socketService:

getUpdates() {
    let sub = new Subject();
    let subObservable = from(kioskSub)

   this.socket.on('receive', (updates: any) => {
     sub.next(updates);
   });
   this.socket.on(`master_receive`, (status: any) => {
        sub.next(JSON.stringify(status));
        if (status.action && status.action === 'stop') {
            sub.complete();
        } // i want to stop subscription here
        if (status.action && status.action === 'start') {
            sub.next(JSON.stringify(status));
        } // and start here
    });
   return subObservable;
}

Component: // 我在哪里订阅 getUpdates

 this.subscription = this.socketService.getUpdates().subscribe((latestdata: string) => {
       this.status = JSON.parse(latestStatus);
  });

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    您可以使用相同的主题sub根据status.action的值订阅/取消订阅。 sub.complete() 完成了 observable 流,因此 observable 不会发出更多值。

     getUpdates() {
        let sub = new Subject();
        let subObservable = from(kioskSub)
    
       this.socket.on('receive', (updates: any) => {
         sub.next(updates);
       });
       this.socket.on(`master_receive`, (status: any) => {
            sub.next(JSON.stringify(status));
            if (status.action && status.action === 'stop') {
                sub.unsubscribe();
            } // i want to stop subscription here
            if (status.action && status.action === 'start') {
                sub.next(JSON.stringify(status));
            } // and start here
        });
       return sub;
    }
    

    【讨论】:

    • 感谢您的回答,但上述解决方案对我不起作用,因为我收到 ObjectUnsubscribedErrorImpl errr
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多