I have a service that needs to make decisions based on the value of a variable stored in the AppState
. Here is a simplified example of my service:
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
interface AppState {
foo: boolean;
}
@Injectable()
export class FooProvider {
private isFoo: boolean;
constructor(private store: Store<AppState>) {
// Check if it's foo
store.pipe(select('foo')).subscribe((foo: boolean) => {
this.isFoo = foo;
});
}
isItFoo = (): string => this.isFoo ? "it's foo!" : 'nope, not foo';
}
Question: Is this the correct way to access and use a variable stored in the
AppState
within a class when using@ngrx/store
?
In a Component
, I could use the foo
variable more simply with the async
pipe like this:
import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
interface AppState {
foo: boolean;
}
@Component(
selector: 'foo-component',
template: `<p>{{ ( foo$ | async ) ? "it's foo!" : "nope, not foo" }}</p>`
)
export class FooComponent {
private foo$: Observable<boolean>;
constructor(private store: Store<AppState>) {
this.foo$ = store.pipe(select('foo'));
}
}
Is there a better or easier way to access state variables within a class?