Overview
TheAuthService is a core Angular service that manages user authentication state, session storage, and provides reactive streams for authentication status. It handles JWT tokens, user information, and login/logout operations.
Import
Properties
EventEmitters
The service usesBehaviorSubject internally to provide reactive authentication state:
Internal subject that emits the current user’s email address
Internal subject that emits the current authentication status
Methods
setUserSession
Stores the complete user session including auth token and user information.The authenticated user object containing email and name
The JWT authentication token returned from the server
setAuthToken
Stores the authentication token in session storage and updates login state.The JWT token to store
getAuthToken
Retrieves the current authentication token from session storage.The stored JWT token, or null if not authenticated
isLoggedInObservable
Provides an Observable stream of the user’s authentication status.Observable that emits
true when user is logged in, false otherwisesetUserMail
Stores the user’s email address in session storage.The user’s email address
getUserMail
Retrieves the user’s email address from session storage.The user’s email address, or null if not set
getUserMailObservable
Provides an Observable stream of the user’s email address.Observable that emits the current user’s email or null
setUserName
Stores the user’s name in session storage.The user’s display name
getUserName
Retrieves the user’s name from session storage.The user’s name, or null if not set
logOut
Clears all user session data and resets authentication state.- Removes auth token from session storage
- Removes user email from session storage
- Removes user name from session storage
- Removes user ID from session storage
- Emits
nullto userMailSubject - Emits
falseto userLoggedInSubject
Storage Keys
The service uses the following session storage keys:authToken- JWT authentication tokenuserMail- User’s email addressuserName- User’s display nameuserId- User’s unique identifier
Usage Example
Related
- UserService - For login and registration endpoints
- AuthUser Model - User data structure
- AuthGuard - Route protection using AuthService
- AuthInterceptor - Automatic token injection