AsyncSubject 是另一个 Subject 变体,只有当 Observable 执行完成时(执行 complete()
),它才会将执行的最后一个值发送给观察者。
import { Component, OnInit } from '@angular/core';
import { AsyncSubject } from 'rxjs/AsyncSubject'; @Component({
selector: 'app-subject',
templateUrl: './subject.component.html',
styleUrls: ['./subject.component.css']
})
export class SubjectComponent implements OnInit { constructor() { } ngOnInit() {
const subject: AsyncSubject<string> = new AsyncSubject<string>();
subject.next('Leo');
subject.subscribe( // 观察者A订阅
(val: string) => {
console.log(`observerA: ${val}`);
}
);
subject.next('Raph');
subject.subscribe( // 观察者B订阅
(val: string) => {
console.log(`observerB: ${val}`);
}
);
subject.next('Mikey');
subject.next('Don');
subject.complete();
} }