2016-05-27 7 views
3

rxJSでサブスクリプションとオブザーバブルを把握しようとしています。未定義(rxJS - サブスクリプション)のプロパティ 'unsubscribe'を読み取ることができません

Observableの間隔を解除して変更し、新しい間隔設定を使用して再登録したいとします。

私はこの分野の初心者ですから、少し助けが必要かもしれません。

あなたはgetTimeメソッド内でサブスクリプションを返す必要があり、このplunk

export class AppComponent implements OnInit { 
    title = 'Observable Interval - Changing interval'; 
    currentTime: any; 
    refreshInterval: number = 1000; 
    private subscription: Subscription; 

    constructor(private timeService: TimeService) { 
    } 

    clicked($event) { 
    console.log('new refreshInterval: ' + this.refreshInterval); 

    // Here I would like to unsubscribe to the subscription 
    // and then resubscribe using the new interval. 
    // However using below statement causes a 
    // TypeError: Cannot read property 'unsubscribe' of undefined 
    this.subscription.unsubscribe(); 
    this.getTime(); 
    } 

    // with this implementation changing the refreshInterval won't have any affect. 
    getTime() { 
      this.timeService.getTime(this.refreshInterval) 
       .subscribe(t => { 
       this.currentTime = t; 
       } 
      ); 
    } 

    ngOnInit() { 
    this.subscription = this.getTime(); 
    console.log(this.subscription); 
    console.log('refreshing each ' + this.refreshInterval + ' ms'); 
    } 
} 

答えて

2

を参照してください:あなたのケースで

getTime() { 
    return this.timeService.getTime(this.refreshInterval) // <----- 
      .subscribe(t => { 
      this.currentTime = t; 
      } 
     ); 
} 

、何も返されません。そのため、未定義のエラーがあります。

関連する問題