Search code examples
angulardependency-injectionngrxngrx-store

ngrx/store Inject a store into a service


I'm using ngrx/store v4.0.2, with Angular 4.3.3.

What I'm trying to do is access the store from within the service:

/********* Module *************/
import { StoreModule, Store } from '@ngrx/store';

@NgModule({
imports: [
    CommonModule,
    StoreModule.forFeature('feature1', reducers),
     //...
     ],
declarations: [ /*...*/ ],
exports: [],
providers: [
    AuthDataService
]
export class MyModule { }

/********* AuthDataService *************/
import { Store } from '@ngrx/store';
import { AuthDataState } from '../reducers/auth';

export class AuthDataService {
    constructor(private state: Store<AuthDataState>){
        this.state.select(getIsLoggedIn).subscribe(in => {
              console.log("User 'loggedIn' is now set to:" + in);
         });
    }
}

However, I'm always getting undefined, while the store works just fine for components in the same module.

How can access the same store that's available to components, but from within the service?

Here's the plunk: http://plnkr.co/edit/1Lxq82

Edit - issue fixed
The issue was with the getIsLoggedIn. It was:

export const getIsLoggedIn = (state: AuthDataState) => state.IsLoggedIn;

It should've been:

export const getIsLoggedIn = createFeatureSelector<AuthDataState>('feature1');

Solution

  • I found a few errors in your plnkr

    1.) You need to prefix the tracker service with @Injectable()

    2.) Your wasInjected on the tracker service was asking == null and if it was not null, it would return false, and that did not make sense if you were asking the question "Was Injected". So I inverted that check.

    Updated the plnkr here http://plnkr.co/edit/KVLpHS