RxJS之BehaviorSubject
Subject 的其中一个变体就是 BehaviorSubject
,它有一个“当前值”的概念。它保存了发送给消费者的最新值。并且当有新的观察者订阅时,会立即从 BehaviorSubject
那接收到“当前值”。
import { Component, OnInit } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Component({ selector: 'app-subject', templateUrl: './subject.component.html', styleUrls: ['./subject.component.css'] }) export class SubjectComponent implements OnInit { constructor() { } ngOnInit() { const subject: BehaviorSubject<string> = new BehaviorSubject<string>('Leo'); subject.subscribe( // 观察者A订阅 (val: string) => { console.log(`observerA: ${val}`); } ); subject.next('Raph'); subject.next('Mikey'); subject.subscribe( // 观察者B订阅 (val: string) => { console.log(`observerB: ${val}`); } ); subject.next('Don'); } }