2017-08-04 28 views
3

在angular 2中,mySubject(請參閱代碼)編譯complete()函數,但它在執行期間出錯,表示沒有此函數。我無法獲得onComplete()來編譯。如何發信號通知流完成的BehaviorSubject

import { Component, OnInit } from '@angular/core'; 
    import { NgForm } from '@angular/forms'; 
    import * as Rx from "rxjs"; 
    import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 

    @Component({ 
     selector: 'app-home', 
     templateUrl: './home.component.html', 
     styleUrls: ['./home.component.scss'] 
    })  
    export class HomeComponent { 
     myBehavior: any; 
     mySubject: BehaviorSubject<string>; 
     received = "nothing"; 
     chatter: string[]; 
     nxtChatter = 0; 
     constructor() { 
     this.myBehavior = new BehaviorSubject<string>("Behavior Subject Started"); 
     this.chatter = [ 
      "Four", "score", "and", "seven", "years", "ago" 
     ]   
    }   

     Start() { 
     this.mySubject = this.myBehavior.subscribe(
      (x) => { this.received = x;}, 
      (err) => { this.received = "Error: " + err; }, 
     () => { this.received = "Completed ... bye"; } 
     ); 
    }   

     Send() { 
     this.mySubject.next(this.chatter[this.nxtChatter++]); 
     if (this.nxtChatter >= this.chatter.length) { 
      this.nxtChatter = 0; 
      this.mySubject.complete(); 
     }  
     }  
    }   

回答

4

這條線:

this.mySubject = this.myBehavior.subscribe(

返回訂閱對象,而不是主題。訂閱沒有completenext函數。要觸發主題complete請執行以下操作:

this.myBehavior.complete(); 

和這裏你在訂閱觸發next

this.mySubject.next(this.chatter[this.nxtChatter++]); 

需要觸發它的主題:

this.myBehavior.next(this.chatter[this.nxtChatter++]); 
相關問題