【发布时间】:2020-04-05 19:38:31
【问题描述】:
我创建了服务ServiceA 和ComponentA。 ServiceA 需要订阅ActivatedRoute 的queryParams,但我想有条件地订阅,条件是提供给ComponentA 的解析器数据。
我的解决方案是检查ComponentA 的onInit 中的条件,并根据它订阅ServiceA 到queryParams。但是,我最初想在服务的构造函数中订阅queryParams,然后以某种方式注入数据。你怎么看?谢谢。
class ServiceA {
constructor (private _route: ActivatedRoute) {}
subscribeToQueryParams() {
this._route.queryParams
.subscribe(params => {
...
});
}
}
class ComponentA implements OnInit {
constructor (private serviceA: ServiceA, private _route: ActivatedRoute) {}
ngOnInit() {
this._route.data.subscribe(condition => {
if(condition) {
this.serviceA.subscribeToQueryParams();
}
});
}
}
【问题讨论】: