RxJs BehaviorSubject的next()方法在服务中 [英] RxJs BehaviorSubject's next() method in service
问题描述
我使用以下方法来在添加新记录后刷新Details
页面.在更新记录后,我也需要刷新.
EventProxyService
export class EventProxyService {
private eventTracker = new BehaviorSubject<any>();
getEvent(): Observable<any> {
return this.eventTracker.asObservable();
}
setEvent(param: any): void {
this.eventTracker.next(param);
}
}
CreateComponent:
export class CreateComponent implements OnInit {
constructor(private eventProxyService: EventProxyService) { }
create(param: any): void {
//other staff related to creating record
this.eventProxyService.setEvent(param);
}
}
DetailsComponent:
export class DetailsComponent implements OnInit {
subscription;
constructor(private eventProxyService: EventProxyService) { }
ngOnInit() {
this.subscription = this.eventProxyService.getEvent().subscribe((param: any) => {
this.refresh(param);
);
}
refresh(param) {
this.record = param; //update record via new one passed from service
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
这种方法效果很好,但是我对以下问题感到有些困惑:
1)因为我也像create()
方法一样在update()
方法中调用this.eventProxyService.setEvent(param);
,所以在我的服务级别而不是组件级别中调用它是个好主意吗? >
2)在上面的CreateComponent
中触发next()方法时有什么问题吗?
我认为 解决方案
I think your design is pretty much fine with BehaviourSubject
(at least in my prospective).
One thing I can advice is use BehaviourSubject
in the root scope singleton service. (which i can't notice in your case)
what if I call the setEvent() in the create() method of my service (not this proxyService, I meant other service where I keep my CRUD methods)
If I Understood your question properly, Answer is NO.
Because calling a service method from another service is not Advisable, So keep things simple.In real world projects once the CRUD methods gets executed then we will try to refresh the data from the Component itself with the help of Service methods (but not in the service).
I call the next() via setEvent() method in the CRUD methods, after create, update, delete operations are completed. Is it a good approach, it is there a better way in real world examples e.g. calling next() in the service (CRUD) as I asked in the first question
Yes, it is a good approach.
这篇关于RxJs BehaviorSubject的next()方法在服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!