0
votes

I have seen authServices where there is a boolean or user object and another component with a nav which displays different buttons depending on the log status.

So the service is injected in the component and observable is created in the authService so the component can subscribe to the boolean. My question is why using observable and not just using the already injected instance of the service:

<nav>
    <ul *ngIf="!this.authService.isAuth">
        <li><a routerLink="/home">Home</a></li>
        <li><a routerLink="/login">Login</a></li>
    </ul>
</nav>

from the already injected service:

constructor(private authService: AuthService) {
}

I have seen examples where the component subscribed to an observable in the auth service so it would be like:

isAuth: Observable<boolean> //in the authService
this.authService.isAuth.subscribe(x => this.isAuth= x)

Why using observable when you can do it the first way?

1
in your code, you inject the authService as private, so you won't be able to use it in the tempalte (html) file - flowest
@flowest My whole application is using it that way right now and it is working. The auth service has @Injectable({ providedIn: 'root' }) and I am injecting it as in my components as private and using it in the templates - ivaylo
It's a matter of taste. Object references are hard to find in html if, for example, you refactor your service code. Personally I prefer my html to be dependant on the component code only. - Silvermind

1 Answers

0
votes

Here it's good (best practice) to use BehaviorSubject without subscribe it in the component

html

<ul *ngIf="!(isAuth | async)">

component.ts

isAuth: Observable<boolean> = this.authService.isAuth;