Angular订阅者模式
2019-05-09 本文已影响0人
曼珠沙华_521b
相当于一个事件发射器,是唯一能够向多个Observer广播值的唯一手段。
在angular6中亲自验证过,
import {Injectable} from '@angular/core';
import {ReplaySubject} from "rxjs";
import {Observable} from 'rxjs/Observable';
@Injectable({
providedIn:'root'
})
export classs CustomerService{
constructor(){}
private subject :ReplaySubject<any>=new ReplaySubject<any>();
// 需要发送的信息
public send(message:any):void{
this.subject.next(message)
}
//需要接收的信息
public get():Observable<any>{
return this.subject.asObservable();
}
}
在组件中发送,首先先导入这个事件服务
constructor(){private customer :CustomerService}
ngOnInit(){
this.customer.send({a:'1',b:'2'})
}
在组件中接收。首先先导入服务
constructor(){private customer :CustomerService}
ngOnInit(){
this.customer.get().subscribe((res)=>{
this.a=res.a;
this.b=res.b;
})
}
在接收的过程中可能会报错,要加上定时器
this.customer.get().subscribe((res)=>{
setTimeout(()=>{
this.a=res.a;
this.b=res.b;
})
})
}
![](https://img.haomeiwen.com/i5793792/2a12b68d726eae19.png)