代码之家  ›  专栏  ›  技术社区  ›  Wagner Moreira

订阅订阅和取消订阅不是一项功能

  •  1
  • Wagner Moreira  · 技术社区  · 7 年前

    我试图取消订阅Observable,发现以下错误:

    [ts] Property 'unsubscribe' does not exist on type 'Observable<number>'. Did you mean 'subscribe'?
    

    此错误与代码有关: this.subscription.unsubscribe();

    以下是整个文件:

    import { Component, Input, OnInit } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { IntervalObservable } from 'rxjs/observable/IntervalObservable';
    
    import 'rxjs/add/observable/interval';
    import 'rxjs/add/observable/timer';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.sass']
    })
    
    export class AppComponent implements OnInit {
      public counting: boolean;
      public triggerBtnText = 'GO!';
      public subscription: Observable<number>;
    
      @Input() count = 0;
    
      constructor() {}
    
      ngOnInit() {
        this.counting = false;
      }
    
      toggleStopwatch(): any {
        if (this.counting === false) {
          this.counting = true;
          this.triggerBtnText = 'STOP';
          this.updateCount()
        } else {
          this.counting = false;
          this.triggerBtnText = 'GO!';
          this.subscription.unsubscribe();
        }
      }
    
      updateCount() {
        this.subscription = Observable.interval(1000);
        this.subscription.subscribe(this.counter);
      }
    
      public counter(value) {
        this.count = value;
        console.log(value);
      }
    
      resetCount() {
        this.count = 0;
      }
    
    }
    

    https://bitbucket.org/wtkd/learning-rxjs/branch/moving-to-ng

    1 回复  |  直到 7 年前
        1
  •  1
  •   jeddai    7 年前

    为了使您可以稍后再订阅,但也可以停止侦听可观察对象,您可以对可观察对象使用不同的函数,称为 takeWhile . 传递一个返回布尔值的谓词( () => { return true || false; } )到takeWhile函数,如果返回true,则继续侦听。你的 counting 变量将与此配合使用。有关工作示例,请参阅下面的代码:

    建议代码:

    this.subscription
    .takeWhile(() => {      // by calling takeWhile and passing in a predicate, 
      return this.counting; // you can have the subscription stop when the counting 
    })                      // variable is false.
    .subscribe((value) => {
      this.counter = value;
    });
    

    还要确保卸下 .unsubscribe() toggleStopwatch() 作用