Subject,在RxJS中是一類特殊的Observable(可觀察對象),它可像多個Observer(觀察者)推送值。
每個Subject也能夠做爲Observer(觀察者) Subject一樣也是一個由next(v),error(e),和complete()這些方法組成的對象。調用next(theValue)方法後,Subject會向全部已經在其上註冊的Observer多路推送theValue。segmentfault
一、建立一個subjectService,實現可觀察以及推送推功能this
import {Injectable} from "@angular/core"; import { ReplaySubject } from "rxjs/ReplaySubject"; import { Observable } from "rxjs/Observable"; import 'rxjs/add/observable/of'; @Injectable() export class SubjectService { private _subject: ReplaySubject<string> = new ReplaySubject<string>(1); //新建一個可觀測可觀測 setCurrentValue(value: string): Observable<boolean> { //設置值 this._subject.next(value); return Observable.of(true); } currentValue(): Observable<string> {//推送值 return this._subject.asObservable(); } }
二、在組建中設置須要推送的值spa
constructor(private _subjectService: SubjectService) { } setValue() { this._subjectService.setCurrentValue('value').subscribe((result: boolean) => { if (!result) { console.log('可觀察者設定失敗'); return; } console.log('可觀察者設定成功'); }); }
三、訂閱、可訂閱多個對象code
subjectValue = ''; constructor(private _subjectService: SubjectService) { } ngOnInit() { this._subjectService.currentValue().subscribe((data: string) => { if (!data) { console.log('獲取失敗'); return; } this.subjectValue = data; }); }
參考網址server
https://segmentfault.com/a/1190000005069851對象