Angular & passing data between components: use cases for Resolve guard vs Service injection

401 views Asked by At

In Angular there are multiple ways to pass data to a Component, in particular one can use a Resolve guard to load the data even before the Component is created so that it is always available or one can inject a Service in the constructor of the Component and subscribe to its data$ stream and start with nothing or maybe a default while waiting for the actual data to load.

I cannot understand when one approach may be preferable or more suitable to use vs the other, online examples are all about simply not showing an empty interface to the user. But developers can create a placeholder interface (skeleton / phantom stuff) while loading the data, and this can actually be a better user experience anyway, so what's the point? The UI will not be blocked for the user.

So, are there specific use cases or edge cases when one approach should be used? Or is it simply a matter of taste given my assumptions? I know that in absolute terms there is no "better choice" than the other, I just want to understand with examples if possible.

1

There are 1 answers

1
Roman A. On

The best approach of passing data to the components it's leveraging of DI providers. This is my personal choice, but I will try to describe in the 1st point. This approach is good for middle-to-large apps.

enter image description here

Why?

  1. It's data-provider-undependable. You can easily change your data producers or data transformations in your provider and inject that provider to the component. Very popular case when we use route.snapshot inside a component and get some data from it. This makes your component route-dependable and if you move this component to another part of app it will doesn't work. But when you put all logic of getting data into providers it will makes your component more flexible. Always think about, "do i can to easily reuse my component in another part of the app" and after that you will understand the "providers idea".
  2. We can easily change provider if we need to shift to another data producer, but it won't affect our components.
  3. Our component has less lines of code.
  4. Easy to test components and providers.

If your app is small-to-middle it's ok to use resolvers and guards, but try to avoid using some route binding (just popular case) in your presentational components. The good example of using of the resolvers and guards is to dispatch the actions inside the components and then get all your data from the store.

If your app is middle-to-large the best approach to leverage the private DI providers.

This answer was inspired by one cool post from Indepth.dev.