How to signal the BehaviorSubject that the stream has finished

In angular 2 mySubject (see code) compiles the complete () function, but at runtime it fails saying that there is no such function. I was unable to get onComplete () to compile.

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

      

+3


source to share


1 answer


This line:

this.mySubject = this.myBehavior.subscribe(

      

returns a subscription object, not an object. And the subscription has no function complete

or next

. To call complete

for an object, do the following:

this.myBehavior.complete();

      



And also here you are calling next

by subscription:

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

      

You need to call it on this question:

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

      

+4


source







All Articles