在我一直关注的大多数教程中,他们说总是在构造函数中进行订阅,例如:
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;
});
}
}发布于 2020-10-26 11:59:50
是的,在onInit()方法中订阅是很好的做法。
我建议只使用构造函数来声明依赖注入。
但是,在这种特殊情况下,当您离开组件时可能会遇到错误,因为当您调用put (您将代码放入一个if语句中)时,您的子赋值可能等于未定义的。您可以声明您的params是可以观察到的,以防止这种情况发生:
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值并重新触发您的逻辑。
发布于 2020-10-26 11:39:24
更好的做法是将Subscription放到ngOnInit()中,因为您希望尽快初始化数据并在访问组件和更新UI时直接显示数据。
不会产生任何后果,因为您已经在.unsubscribe()步骤中使用了ngOnDestroy()。
https://stackoverflow.com/questions/64536343
复制相似问题