Как сигнализировать BehaviorSubject о завершении потока

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

person Yogi Bear    schedule 04.08.2017    source источник


Ответы (1)


Эта строка:

this.mySubject = this.myBehavior.subscribe(

возвращает объект подписки, а не тему. И у подписки нет функции complete или next. Чтобы вызвать complete по теме, сделайте следующее:

this.myBehavior.complete();

А также здесь вы запускаете next при подписке:

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

Вам нужно вызвать его по теме:

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

Чтобы узнать больше о BehaviorSubject см. этот ресурс.

person Max Koretskyi    schedule 04.08.2017