环境:Angular2+现在有一个组件内部classDemo01{data$:Observable;constructor(privateservice:MyService){}OnInit(){this.data$=this.service.getData();}submit(){//在这里我需要拿到this.data$中的数据去做一些处理//如果直接对this.data$进行订阅的话,就会进入MyService中的getData()方法重新获取一次数据,但是我不想这样//**目前我的办法是,看下面的ts**}}Service:classMyService{getData():Observable{returnof(['1','2','3','4'])//这里有可能是个http请求}}模板:{{item}}Submit我的解决办法是:classDemo01{data$:Observable;data:string[]constructor(privateservice:MyService){}OnInit(){this.data$=this.service.getData().pipe(//使用tap操作符监控this.data$,将其中的数据缓存一份到this.datatap(data=>{this.data=data;}));}submit(){//在这里使用this.data}}不知道是否还有其他的操作能够解决这种场景呢?
2 回答

弑天下
TA贡献1818条经验 获得超8个赞
找到答案了,使用publishReplay和refCount操作符classDemo01{data$:Observable; data:string[]constructor(privateservice:MyService){}OnInit(){//使用这2个操作符,会把'冷'的变成'热'的this.data$=this.service.getData().pipe(publishReplay(),refCount());}submit(){//即使当前this.data$被绑定到模板中了,在这里再次订阅this.data$,也不会执行service中的getData()方法中Observable内部的of()方法this.data$.subscribe((array)=>{})}}参考

慕神8447489
TA贡献1780条经验 获得超1个赞
我理解问题是,一个请求完成后,多处调用时不想再次请求。。如果我理解正确的话,那存在service中,多处注入该service就好了。。何必这么麻烦。。service层本身存在就是为了数据通信的。。
添加回答
举报
0/150
提交
取消