Blog>
Snippets

Creating and Using Akita Selectors

Showcase the creation of Akita selectors to derive pieces of data from the store's state tree and how to use those selectors in Angular components.
import { Query } from '@datorama/akita';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface SessionState {
  token: string;
  userName: string;
  // ... other fields
}

@Injectable({ providedIn: 'root' })
export class SessionQuery extends Query<SessionState> {
  // Selectors are defined here
  userName$ = this.select(state => state.userName);
  isLoggedIn$ = this.select(state => state.token).pipe(map(token => !!token));

  constructor(protected store: SessionStore) {
    super(store);
  }
}
This JavaScript code defines the `SessionQuery` class using Akita's `Query` class. It provides two selectors, `userName$` and `isLoggedIn$`, to select `userName` and check if the user is logged in from the `SessionState` in the store.
<div *ngIf="isLoggedIn$ | async as isLoggedIn">
  <span *ngIf="isLoggedIn">Welcome, {{ userName$ | async }}</span>
  <span *ngIf="!isLoggedIn">Please log in.</span>
</div>
This HTML snippet is an Angular template using the `async` pipe to subscribe and display data from the Akita selectors `isLoggedIn$` and `userName$` in the component's template.
import { Component } from '@angular/core';
import { SessionQuery } from './session.query';

@Component({
  selector: 'app-user-component',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {
  userName$ = this.sessionQuery.userName$;
  isLoggedIn$ = this.sessionQuery.isLoggedIn$;

  constructor(private sessionQuery: SessionQuery) {}
}
This JavaScript code defines the `UserComponent` Angular component. It injects the `SessionQuery` and creates properties `userName$` and `isLoggedIn$` that are exposed to the template for rendering. The use of the async pipe in the component's template will subscribe to these observable streams.
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info span {
  margin: 0 10px;
}
This CSS snippet defines styles for the `.user-info` class, which is a hypothetical class we might have used in our user component's template. It ensures that the user info is displayed in a row with space between the elements.