美文网首页
Angular订阅者模式

Angular订阅者模式

作者: 曼珠沙华_521b | 来源:发表于2019-05-09 20:12 被阅读0次

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

相关文章

网友评论

      本文标题:Angular订阅者模式

      本文链接:https://www.haomeiwen.com/subject/twbgoqtx.html