2017-09-28 36 views
1

我想退訂可觀察到的和我看到下面的錯誤:subscription.subscribe和退訂不是一個函數

[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; 
    } 

} 

這裏一個簡單的項目中,也可以是泰斯特d:https://bitbucket.org/wtkd/learning-rxjs/branch/moving-to-ng

+1

發佈確切且完整的異常堆棧跟蹤。但是,您選擇輸入任何類型的訂閱,從而消除TypeScript將爲您執行的所有類型檢查,並非訂閱。這是一個可觀察的。 Observable中沒有取消訂閱方法。不要使用任何。爲您的變量提供適當的類型,並且TypeScript將在構建時發現您的編程錯誤。這是TypeScript的重點。 –

+1

我不記得確切,但有Observable.interval和Angular需要使用'import {IntervalObservable} from'rxjs/observable/IntervalObservable';' – rjustin

+0

@ JBNizet堆棧跟蹤已添加,TY爲打字稿提示,你知道嗎我怎樣才能使這些觀察結果能夠被觀察? –

回答

1

爲了使這樣以後可以訂閱回來,但也停止監聽對觀察到的,你可以對觀測稱爲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; 
}); 

此外,一定要刪除您toggleStopwatch()函數的調用.unsubscribe()

已更新以反映問題更改,請參閱原始答案的修訂。