Implementing Authentication State with Akita
Provide an example of managing authentication state, such as user login and logout, using Akita in an Angular application.
import { Injectable } from '@angular/core';
import { Store, StoreConfig } from '@datorama/akita';
export interface AuthState {
token: string | null;
isLoggedIn: boolean;
}
export function createInitialState(): AuthState {
return {
token: null,
isLoggedIn: false
};
}
@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'auth' })
export class AuthStore extends Store<AuthState> {
constructor() {
super(createInitialState());
}
}
Defines the store for authentication state using Akita. It includes the initial state which represents whether a user is logged in or not and their token.
import { Injectable } from '@angular/core';
import { Query } from '@datorama/akita';
import { AuthStore, AuthState } from './auth.store';
@Injectable({ providedIn: 'root' })
export class AuthQuery extends Query<AuthState> {
isLoggedIn$ = this.select(state => state.isLoggedIn);
token$ = this.select(state => state.token);
constructor(protected store: AuthStore) {
super(store);
}
}
Creates a query class for the authentication state which allows for selecting parts of the state, such as `isLoggedIn` and `token` using observables.
import { AuthStore } from './auth.store';
export class AuthService {
constructor(private authStore: AuthStore) {}
login(token: string) {
this.authStore.update({
token: token,
isLoggedIn: true
});
}
logout() {
this.authStore.update(createInitialState());
}
}
Defines an authentication service that interacts with the AuthStore to update the login state and token on login, and resets on logout.
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
This is the HTML template for login and logout buttons. Clicking these buttons will trigger the corresponding functions.
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
import { AuthQuery } from './auth.query';
@Component({
selector: 'app-auth-buttons',
template: `...
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
`, // the template code from the previous JSON object goes here.
})
export class AuthButtonsComponent {
isLoggedIn$ = this.authQuery.isLoggedIn$;
constructor(private authQuery: AuthQuery, private authService: AuthService) {}
login() {
const token = 'sample-token'; // In a real app, you would get this token from a login service
this.authService.login(token);
}
logout() {
this.authService.logout();
}
}
This Angular component uses the AuthService to login and logout, and AuthQuery to observe the logged-in status. It provides the functionality for the login and logout buttons.