-1

I'm testing angular6 + loopback... At my step, I'm able to create my account and login, so I get back an user object with the informations of the logged user...

In my templates, I have some items I want to show only for logged users. So I make a service which will send an Observable, and according its value, I show or not the item in each component that I need...

But, to do it, I need in each component, call my service, create again a subscription to my Observable..

And sometime I have several nested components for which I need to check if the user is logged or not. So it seems redundant to retype the same code several times while it is already available for one component on the page.

So my question is... Should I realy have to make a subscription for each component, or there is a way to make a global service subscription or got inherit subscription from the parent component ? What the best practice ?

I make some test by create a global.ts file with an object in which I put my user login data after login, then I just import this file in each component, so I can use easily where I need, but I'm not sure it's a good practice for it and I meet some issue with this method.

Any suggestion are welcome.

Best,

Mike

Mike5
  • 61
  • 11

1 Answers1

0

You should implement a structural directive that adds/removes the element based on whether the user is authenticated.

Really nice article about structural directives where they create similar directive that adds/removes the content based on user role.

Ludevik
  • 6,954
  • 1
  • 41
  • 59
  • In this article, they use @input to share data between components... It's good to know, homeover, we can't bind a data in the with this method.. As my goal is to share data at the top level of the application, it seem the only way will be to add data directly in the routes object. But for now I don't find a way to add the result of my Service as data. – Mike5 Sep 27 '18 at 15:52
  • You should use router guards to prevent the state from activating when it shouldn't, ie. when the user is not logged in, and structural directive when you want to prevent part of component from rendering. – Ludevik Sep 27 '18 at 18:17