在我一直关注的大多数教程中,他们说总是在构造函数中进行订阅,即:
constructor(private eventDetailsService: EventDetailsService) {
this.subscription1 = this.eventDetailsService.reload$
.subscribe(
response => {
this.eventDetail = response;
});
}
然后销毁ngDestroy中的订阅:
ngOnDestroy() {
this.subscription1.unsubscribe();
}
我有一个特殊的组件,需要首先在ngOnInit
内做一些逻辑来锻炼是否首先需要调用订阅。它可以让我在ngOnInit
内进行订阅而没有任何错误,但是我想知道这样做是否有后果?
ngOnInit() {
if ((this.activatedRoute.parent.snapshot.parent.params.eventId != undefined))
{
this.subscription1 = this.eventDetailsService.reload$
.subscribe(
response => {
this.eventDetail = response;
});
}
}
答案 0 :(得分:3)
是的,订阅onInit()方法是一种很好的做法。
我建议仅使用构造函数来声明依赖项注入。
但是在这种特殊情况下,离开组件时可能会出错,因为调用destroy(将代码放入if语句中)时,您的订阅可能等于未定义。
您可以将参数声明为可观察的参数,以防止出现这种情况:
ngOnInit() {
const eventId$ = this.route.parent.parent.params.pipe(
map((params: Params) => params.get('eventId')),
filter(id => !!id)
);
this.subscription = eventId$.pipe(
mergeMap(() => this.eventDetailsService.reload$())
).subscribe(response => {
this.eventDetail = response;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
这样做,只有当您的路由中具有eventId参数并且您的订阅在销毁组件后可以安全地取消订阅时,您的观察对象才会发出。
另外,如果您使用不同的eventId参数导航到同一组件,则此可观察对象将发出新的eventId值并重新触发您的逻辑。
答案 1 :(得分:-1)
甚至最好将Subscription
放入ngOnInit()
,因为您希望尽快初始化数据并在访问组件和更新UI时直接显示数据。
没有任何后果,因为您在.unsubscribe()
步骤中已经ngOnDestroy()
。