一 Subject主题
Subject是Observable的子类。- Subject是多播的,允许将值多播给多个观察者。普通的 Observable 是单播的。
在 Subject 的内部,subscribe 不会调用发送值的新执行。它只是将给定的观察者注册到观察者列表中,类似于其他库或语言中的 addListener 的工作方式。
要给 Subject 提供新值,只要调用 next(theValue),它会将值多播给已注册监听该 Subject 的观察者们。
1import { Component, OnInit } from '@angular/core'; 2import { Subject } from 'rxjs/Subject'; 3import { Subscription } from 'rxjs/Subscription'; 4 5@Component({ 6 selector: 'app-subject', 7 templateUrl: './subject.component.html', 8 styleUrls: ['./subject.component.css'] 9}) 10export class SubjectComponent implements OnInit { 11 12 constructor() { } 13 14 ngOnInit() { 15 const subject: Subject<string> = new Subject<string>(); 16 const subscriptionA: Subscription = subject.subscribe( 17 (val: string) => { 18 console.log(`observerA: ${val}`); 19 } 20 ); 21 const subscriptionB: Subscription = subject.subscribe( 22 (val: string) => { 23 console.log(`observerB: ${val}`); 24 } 25 ); 26 subject.next('Mikey'); 27 subject.next('Leo'); 28 subscriptionA.unsubscribe(); // 取消订阅 29 subscriptionB.unsubscribe(); // 取消订阅 30 subject.next('Raph'); 31 subject.complete(); 32 } 33 34}

每个 Subject 都是观察者。 - Subject 是一个有如下方法的对象: next(v)、error(e) 和 complete() ,可以把 Subject 作为参数传给任何 Observable 的 subscribe 方法。
1import { Component, OnInit } from '@angular/core'; 2import { Subject } from 'rxjs/Subject'; 3import { Subscription } from 'rxjs/Subscription'; 4import { from } from 'rxjs/observable/from'; 5import { Observable } from 'rxjs/Observable'; 6 7@Component({ 8 selector: 'app-subject', 9 templateUrl: './subject.component.html', 10 styleUrls: ['./subject.component.css'] 11}) 12export class SubjectComponent implements OnInit { 13 14 constructor() { } 15 16 ngOnInit() { 17 const subject: Subject<string> = new Subject<string>(); 18 const subscriptionA: Subscription = subject.subscribe( 19 (val: string) => { 20 console.log(`observerA: ${val}`); 21 } 22 ); 23 const subscriptionB: Subscription = subject.subscribe( 24 (val: string) => { 25 console.log(`observerB: ${val}`); 26 } 27 ); 28 29 const observable: Observable<string> = from(['Raph', 'Don']); 30 observable.subscribe(subject); 31 32 } 33 34}
