代码之家  ›  专栏  ›  技术社区  ›  Yogi Bear

如何向行为主体发出流已完成的信号

  •  9
  • Yogi Bear  · 技术社区  · 9 年前

    在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();
            }    
           }    
        }        
    
    1 回复  |  直到 9 年前
        1
  •  10
  •   Michael D    5 年前

    该行:

    this.mySubject = this.myBehavior.subscribe(
    

    返回订阅对象,而不是主题。订阅没有 complete 或 next 作用触发 完成 在该主题上,请执行以下操作:

    this.myBehavior.complete();
    

    这里你也触发了

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

    你需要在主题上触发它:

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

    了解更多信息 BehaviorSubject see this resource