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');
  }

}

RxJS之BehaviorSubject

相关文章:

  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2018-03-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案