Search code examples
asynchronousangularroutesresolver

Asynchronous access to resolved data in Angular2


I'm a little confused with Resolvers for routes. The problem that Resolvers solve for me is that an object is present in the component at rendering time. If I do it without Resolvers and start fetching objects in a component's constructor via Promise, accessing its nested properties in the template like

{{myObj.foo.bar}}

could lead to an error if the Promise does not resolve early enough, which is very likely when a http request needs to be done. However, the little info about receiving resolved objects from a Resolver tells me to do it like this in the component's constructor

this.route.data.subscribe(val => {...});

Isn't this the same sh*t as before? Ok, I admit, that the backend request has already finished, and I'll receive the subscription in no time. Nevertheless, I access the resolved data asynchronously again. There may be a very high chance that {{myObj.foo.bar}} is accessible at template rendering, but there is no guarantee, isn't it?

I don't know if I see that too critical. It's a gut feeling that using canActivate for the route and setting the resolved object to a Service that, in turn, can be accessed by any component synchronously comes closer to my intention, though.

Looking forward to clarifications


Solution

  • Wrap the whole template or parts where you need to access myObj with *ngIf:

    <ng-container *ngIf="myObj?.foo">
      {{myObj.foo.bar}}
    </ng-container>