【问题标题】:How to signal a BehaviorSubject that the stream is completed如何向 BehaviorSubject 发出流已完成的信号
【发布时间】:2017-08-04 19:57:27
【问题描述】:

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

【问题讨论】:

    标签: angular rxjs behaviorsubject


    【解决方案1】:

    这一行:

    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++]);
    

    了解更多关于BehaviorSubjectsee this resource的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多