angular – 如何向BehaviorSubject发信号通知流已完成
发布时间:2020-12-17 17:28:59 所属栏目:安全 来源:网络整理
导读:在angular 2中,mySubject(参见代码)编译了一个complete()函数,但是在执行期间它没有错误,说没有这样的函数.我无法使用onComplete()进行编译. import { Component,OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import * as Rx f
在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(); } } } 解决方法
这一行:
this.mySubject = this.myBehavior.subscribe( 返回订阅对象,而不是主题.订阅没有完整或下一个功能.要触发完成主题,请执行以下操作: this.myBehavior.complete(); 此外,您还会在订阅时触发下一个: this.mySubject.next(this.chatter[this.nxtChatter++]); 您需要在主题上触发它: this.myBehavior.next(this.chatter[this.nxtChatter++]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |