【问题标题】:timer.unsubscribe is not a function Angular2timer.unsubscribe 不是 Angular2 的函数
【发布时间】:2016-10-21 16:10:10
【问题描述】:

试图制作一个简单的计时器,但需要在某些if 条件下打破它。但总是报错EXCEPTION: timer.unsubscribe is not a function

我做错了什么?

    let timer:any = Observable.timer(0,1000);
    timer.subscribe(data => {
            console.log(this.itemsRatedList);
            if(data == 5) timer.unsubscribe();
        });

【问题讨论】:

    标签: angular timer angular2-observables


    【解决方案1】:

    应该是:

    let timer:any = Observable.timer(0,1000);
    let subscription = timer.subscribe(data => {
      console.log(this.itemsRatedList);
      if(data == 5) 
        subscription.unsubscribe();
    });
    

    你不能unsubscribeObservable,只能Subscription

    Plunker example

    【讨论】:

    • 哇...太不考虑我了 :) 谢谢!
    【解决方案2】:

    一个更清晰和简单的例子是this try this example,我认为更清楚。

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Observable } from 'rxjs/Rx';
    
    @Component({
      selector: 'app-slider',
      templateUrl: './slider.component.html',
      styleUrls: ['./slider.component.css']
    })
    
    
    export class SliderComponent implements OnInit , AfterViewInit, OnDestroy {
    
      Sliders: any;
      timer: any;
      subscription: any;
    
    
     constructor() { }
    
     ngOnInit() {
    
       // after 3000 milliseconds the slider starts
       // and every 4000 miliseconds the slider is gona loops
    
       this.timer = Observable.timer(3000, 4000);
    
       function showSlides() {
         console.log('Test');
       }
    
       // This is the trick
       this.subscription = this.timer.subscribe(showSlides);
    
     }
    
      // After the user live the page
      ngOnDestroy() {
        console.log('timer destroyd');
        this.subscription.unsubscribe();
      }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2018-09-03
      • 2017-04-17
      • 1970-01-01
      相关资源
      最近更新 更多