【发布时间】:2019-12-15 12:31:43
【问题描述】:
我使用以下方法在添加新记录后刷新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);
}
}
创建组件:
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) 因为我也在update() 方法中调用this.eventProxyService.setEvent(param);,就像在create() 方法中一样,在我的服务级别而不是组件级别调用它会不会是个好主意? p>
2)上面CreateComponent中触发next()方法有什么问题吗?
【问题讨论】:
-
我不确定我是否理解第一个问题。但是要回答第二个问题,您的 BehaviorSubject 是私有的,因此您将无法从组件中调用它。最好将 BehaviorSubject 设为服务私有,以确保没有其他代码修改它。
-
@DeborahK 感谢您的回复。实际上第一个问题提到如果我在我的服务的 create() 方法中调用 setEvent()(不是这个 proxyService,我的意思是我保留我的 CRUD 方法的其他服务)怎么办?有什么想法吗?
-
@DeborahK 对于第二个问题,我问我在CRUD方法中通过setEvent()方法调用next(),在创建、更新、删除操作完成后。这是一个好方法吗,在现实世界的例子中是否有更好的方法,例如正如我在第一个问题中所问的那样,在服务 (CRUD) 中调用 next()。 有什么想法吗?
标签: angular typescript rxjs behaviorsubject