2

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

Jan B.
  • 6,030
  • 5
  • 32
  • 53
  • There's no guarantee when it will arrive, Just use safety checks `myObj?.foo.bar`, When the value finally gets there, it will rerender. – Paul Samsotha Sep 27 '16 at 10:28
  • That's what I want to avoid. Using dozens of "?" operators in my template. Moreover, the ? operator means that an object is optional. However, on a profile page of a user his phone number may be optional, but the user object is NOT optional, it is mandatory. – Jan B. Sep 27 '16 at 10:34

1 Answers1

2

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

<ng-container *ngIf="myObj?.foo">
  {{myObj.foo.bar}}
</ng-container>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    That would solve the multiplicity of ?s (and would add an extra node in the HTML). Nevertheless I don't see the purpose of accessing data via a ``Subject``, that have already been fetched and are directly accessible. Probably I just am little too bullheaded, but "abusing" the guard pattern as a Resolver, that inject the data into a service makes more sense to me, at least in my particular use case. Thanks anyway. – Jan B. Sep 27 '16 at 21:17
  • 1
    `` isn't added to the DOM (same as ` – Günter Zöchbauer Sep 28 '16 at 02:55
  • Oh, another undocumented feature :). Thanks for bringing this up. I'm still not fully convinced, but this is definitely an option. – Jan B. Sep 28 '16 at 20:46
  • 1
    `` was added very recently. – Günter Zöchbauer Sep 29 '16 at 02:55