Angular订阅者模式

相当于一个事件发射器,是唯一能够向多个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;
})

})
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容