1
votes

I am learning the Angular 5+ and recently comes to the subject/subscription part, I see many tutorial would like to use the subscription in the certain way:

  1. Declare the subscription in component
  2. Subscribe it in ngOnInit via a service's subject or ngrx/store
  3. Unsubscribe it in ngOnDestroy

However, I am not sure if we have to subscribe/unsubscribe every subscription in the component in ngOnInit and ngOnDestroy. For example, if my subscription will get updated through a button click event, which plan should I subscribe it in my component?

  1. Only ngOnInit
  2. Only button click event
  3. Both ngOnInit and button click event

Why would we always subscribe a subscription in ngOnInit? The ngOnInit would be like a Page_Load in page life cycle, so it would only be called once at the very first time, if so whenever the subscription gets updated, will the ngOnInit be fired over and over again? If so, will my component be loaded over and over again which would cause a performance issue if in large application?

1

1 Answers

4
votes

You usually put Observables to subscribe to inside a Service and make them available via getters and setters.

When subscribing to an Observable it behaves in a certain way like an EventListener. Whenever the object inside the Observable gets changed, an Event gets fired and your code inside the subscription gets executed. Additionally, you get provided the updated object.

Even if you init the subscription inside ngOnInit this won't cause your entire Component to reload when an update arrives. Only those parts that get updated by your code inside the subscription.

You don‘t have to put a subscription inside ngOnInit(). It depends on what you want to achieve in the component. But most of the time you want to load and display data directly when you access the component and update the UI when this data changes. That's why it is good practice to put the subscription in ngOnInit().