The Query

A Query is a class offering functionality responsible for querying the store.

You can think of the query as being similar to database queries. Its constructor function receives as parameters its own store and possibly other query classes.

Queries can talk to other queries, join entities from different stores, etc.

To create a Query, you need to extend the Query class from Akita.

session.query.ts
import { Query } from '@datorama/akita';
export class SessionQuery extends Query<SessionState> {
constructor(protected store: SessionStore) {
super(store);
}
}

With this setup you get a Query with the following methods:

  • select<R>(project?: string | (store: S) => R): Observable<R>

    Select a slice from the store:

session.query.ts
nav.component.ts
import { Query } from '@datorama/akita';
export class SessionQuery extends Query<SessionState> {
isLoggedIn$ = this.select(state => !!state.token);
selectName$ = this.select('name');
multi$ = this.select(['name', 'age']) // { name, age }
multi$ = this.select[state => state.name, state => state.age] // [name, age]
constructor(protected store: SessionStore) {
super(store);
}
}
import { SessionQuery } from './session.query';
class NavComponent {
isLoggedIn$: Observable<boolean>;
constructor(private sessionQuery: SessionQuery) {
this.isLoggedIn$ = this.sessionQuery.isLoggedIn$;
}
}

The select() method returns an observable that calls distinctUntilChanged() internally, meaning it will only fire when the state changes, i.e., when there is a new reference.

  • getValue()

The getValue() method returns the raw value of the store.

this.authQuery.getValue();
  • selectLoading()

Select the store's loading state:

this.isLoading$ = this.authQuery.selectLoading();
  • selectError()

Select the store's error state:

this.error$ = this.authQuery.selectError();

Notice that the Query select methods will always return an Observable which pushes the initial value first.