So, I have navbar which is constant throughout my SPA application. I have several links inside it (products, register etc.) for navigation purposes.
When I log in, I want, for example, the Register link to disappear. I've read numerous topics here, none of them helped. Can anyone provide me with good explanation. Here a short version of my approach:
I have login session service which holds data whether some logged in:
Injectable({
providedIn: 'root'
})
export class LoginSessionService {
private isLoggedIn: boolean = false;
public GetIsLoggedIn(): boolean {
return this.isLoggedIn;
}
public SetIsLoggedIn(value: boolean): void {
this.isLoggedIn = value;
this.loggedIn.next(this.isLoggedIn);
}
public loggedIn: Subject<boolean> = new BehaviorSubject<boolean>(false);
}
Then I have the navbar component class which subscribes to this BehaviorSubject, with constructor injection, as usual:
export class WelcomeScreenComponent implements OnInit{
public isLoggedIn: boolean;
constructor(private loginSessionService: LoginSessionService) {
}
ngOnInit(): void {
this.loginSessionService.loggedIn.subscribe(response => this.isLoggedIn = response);
}
getLoggedInfo(): boolean {
return this.isLoggedIn;
}
}
And here is a snippet my html template:
<a *ngIf="getLoggedInfo()" href="link">Shopping Cart</a>
I did this implementation according to the exact same problem in another topic, but for me it still does not work. Also, I have a separate component, in which, when successful login is done, it triggers the whole process with:
private saveLoginSucessInformation() {
this.loginSessionService.SetIsLoggedIn(true);
this.isLoggedIn = this.loginSessionService.GetIsLoggedIn();
}
So, basically I am using the LogionSessionService isLoggedIn as global variable, for which I need to detect the changes and change the html accordingly. I have a feeling that my Lifecycle Hook is not the correct one, because OnInit triggers when starting/ refreshing the App (page).
CodePudding user response:
I think you need to change the method into a getter.
change this:
public GetIsLoggedIn(): boolean {
return this.isLoggedIn;
}
to this:
public get isLoggedIncheck(): boolean {
return this.isLoggedIn;
}
and use in html like:
<a *ngIf="isLoggedIncheck" href="link">Shopping Cart</a>
or you can directly use isLoggedIn
in the html :
<a *ngIf="isLoggedIn" href="link">Shopping Cart</a>
CodePudding user response:
In the WelcomeScreenComponent
there's no need for the getLoggedInfo()
method. The subscription in the ngOnInit()
is enough. Simply put the isLoggedIn
variable of WelcomeScreenComponent
in the *ngIf
in the html,
<a *ngIf="getLoggedInfo()" href="link">Shopping Cart</a>
and it should work.