Yassin Mo I am create a project with angular 17..
after create application app.module.ts file is not available.
I have a seprate module for login.
i have a seprate component for navbar. In the login component i create a property name login. Click on Login Button i have store all data with authenticationService. After storing login data in authentication service i have create a observable like this loggedIn= new BehaviorSubject
get isLoggedIn() {
return this.loggedIn.asObservable();//push Interface
}
in login method send
this.loggedIn.next(true);
and this observale in the app.component.ts
this.isLoggedIn$ = this.authenticationService.loggedIn;
but when i am login this.isLoggedIn$ is not working if i am refresh the page its working fine.
Abhishek YadavPosted Apr 21, 2024, 5:35 PM
It seems like you are facing a sync issue with the authentication state. When you refresh the page, the application reloads and fetches the correct authentication state.
To resolve this issue, you can try the following approaches:
1. Store the authentication state in local storage:
- When the user logs in, store the authentication state in local storage.
- When the application initializes, check if there is any authentication state in local storage and update the authentication service accordingly.
2. Use a route guard:
- Create a route guard that checks if the user is authenticated before navigating to a protected route.
- Update the authentication state in the route guard based on the user's authentication status.
3. Use a resolver:
- Create a resolver that fetches the authentication state before initializing a component.
- Update the authentication state in the resolver based on the user's authentication status.
By implementing one of these approaches, you should be able to ensure that the authentication state is synchronized across the application and it reflects correctly in your isLoggedIn$ observable.
Ankit RaiPosted Apr 21, 2024, 12:37 PM
First time not console.log if refresh the page console.log working
Jobin SPosted Apr 21, 2024, 11:56 AM
this.isLoggedIn$.subscribe((x) => { console.log(x)});