如何向 BehaviorSubject 发出流已完成的信号

How to signal a BehaviorSubject that the stream is completed

在angular2中,mySubject(见代码)编译了一个complete()函数,但是执行时报错说没有这个函数。我无法让 onComplete() 进行编译。

    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();
        }    
       }    
    }        

这一行:

this.mySubject = this.myBehavior.subscribe(

returns 订阅对象,不是主题。订阅没有 completenext 功能。要在主题上触发 complete,请执行以下操作:

this.myBehavior.complete();

此外,您还在此处触发了 next 订阅:

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

您需要在主题上触发它:

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

了解更多 BehaviorSubject see this resource