简体   繁体   English

Angular ngOnInit 允许订阅吗?

[英]Angular subscription allowed in ngOnInit?

In most of the tutorials I've been following, they say to always do a subscription within the constructor ie:在我一直关注的大多数教程中,他们说总是在构造函数中进行订阅,即:

constructor(private eventDetailsService: EventDetailsService) {
      this.subscription1 = this.eventDetailsService.reload$
            .subscribe(
            response => {
                this.eventDetail = response;
            });
}

And then to destroy the subscription within ngDestroy:然后在 ngDestroy 中销毁订阅:

ngOnDestroy() {
        this.subscription1.unsubscribe();
    }

I have a particular component where I need to do some logic within ngOnInit first to workout whether I need to call the subscription in the first place.我有一个特定的组件,我需要首先在ngOnInit中做一些逻辑来确定我是否需要首先调用订阅。 It allows me to do the subscription within ngOnInit without any errors, but I was wondering if there is a consequence of doing this?它允许我在ngOnInit中进行订阅而不会出现任何错误,但我想知道这样做是否会有结果?

ngOnInit() {
   if ((this.activatedRoute.parent.snapshot.parent.params.eventId != undefined))
        {
            this.subscription1 = this.eventDetailsService.reload$
            .subscribe(
            response => {
                this.eventDetail = response;
            });
        }
}

Yes, it's good practice to subscribe in the onInit() method.是的,在 onInit() 方法中订阅是个好习惯。
I would recommend to use your constructor only to declare your dependency injections.我建议只使用你的构造函数来声明你的依赖注入。
In this particular case though, you might run into an error when you leave your component since there's a possibility that your subsciption equals undefined when you call on destroy (you put your code in a if statement).但是在这种特殊情况下,当您离开组件时可能会遇到错误,因为当您调用 destroy 时您的订阅可能等于未定义(您将代码放在 if 语句中)。 You can declare your params as an observable to prevent this:您可以将您的参数声明为可观察的以防止这种情况发生:

    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();
    }

By doing so, your observable will only emit when you have the eventId param in your route and your subscription is safe to be unsubscribed once you destroy the component.通过这样做,您的 observable 只会在您的路由中有 eventId 参数时才会发出,并且一旦您销毁组件,您的订阅就可以安全地取消订阅。
Also, If you navigate to the same component with a different eventId param, this observable will emit the new eventId value and retrigger your logic.此外,如果您使用不同的 eventId 参数导航到同一组件,则此可观察对象将发出新的 eventId 值并重新触发您的逻辑。

It is even good practice to put your Subscription s into the ngOnInit() , as you want to initialize the data as soon as possible and display data directly when you access the component and update the UI.Subscription放入ngOnInit()甚至是一个好习惯,因为您希望尽快初始化数据并在访问组件和更新 UI 时直接显示数据。

There are no consequences, as you already .unsubscribe() in your ngOnDestroy() step.没有任何后果,因为您已经在.unsubscribe() ngOnDestroy()步骤中使用了 .unsubscribe() 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM