Store: Dependency Injection in State - getting Cannot set property ... of undefined

Created on 16 Jul 2018  路  5Comments  路  Source: ngxs/store

Versions

  • @angular: 6.0.5 (All angular packages)
  • @ngxs/devtools-plugin: 3.2.0
  • @ngxs/logger-plugin: 3.2.0
  • @ngxs/router-plugin: 3.2.0
  • @ngxs/storage-plugin: 3.2.0
  • @ngxs/store: 3.2.0

Repro steps

I've upgraded ngxs from 3.1.4 to the newest version and since then i'm getting an error when trying to inject some injectable into the state. I tried also to upgrade angular to 6.0.9 but it didn't work.
Downgrading only @ngxs/store to version 3.1.4 fixes this issue.

export class AuthState {
  constructor(private _authService: AuthService) {}
}

Observed behavior

Getting the error:

core.js:1633 ERROR TypeError: Cannot set property '_authService' of undefined
    at AuthState (auth.state.ts:25)
    at ngxs-store.js:1062
    at Array.map (<anonymous>)
    at fn (ngxs-store.js:1062)
    at Store.push../node_modules/@ngxs/store/fesm5/ngxs-store.js.Store.selectSnapshot (ngxs-store.js:1133)
    at JwtInterceptor.tokenGetter (angular-jwt-options.ts:11)
    at JwtInterceptor.push../node_modules/@auth0/angular-jwt/src/jwt.interceptor.js.JwtInterceptor.intercept (jwt.interceptor.js:67)
    at HttpInterceptorHandler.push../node_modules/@angular/common/fesm5/http.js.HttpInterceptorHandler.handle (http.js:1137)
    at HttpXsrfInterceptor.push../node_modules/@angular/common/fesm5/http.js.HttpXsrfInterceptor.intercept (http.js:1741)
    at HttpInterceptorHandler.push../node_modules/@angular/common/fesm5/http.js.HttpInterceptorHandler.handle (http.js:1137)

Most helpful comment

@eranshmil how did you resolve this issue? I'm having the same problem with a lazy-loaded module.

Thanks

All 5 comments

@eranshmil Is it possible to provide a stackblitz repro?

PS. Has your class got an @Injectable() decorator on it?

The AuthSevice has the decorator.
And I'm using the same code, it happens only after the upgrade.
I'll do my best to provide one later today.

Thanks for the quick comment!

My bad, it happened because of using a state from a lazy-loaded module before it's being initialized.
Still can't figure out why it's working with @ngrx/store 3.1.4.

@eranshmil how did you resolve this issue? I'm having the same problem with a lazy-loaded module.

Thanks

Don't forget to add your new store to it your imports where you define NgxsModule.forRoot(...), in my case it's the the app.module.ts file.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

goodmite picture goodmite  路  5Comments

ToxicToast picture ToxicToast  路  6Comments

splincode picture splincode  路  4Comments

paulstelzer picture paulstelzer  路  5Comments

TomDemulierChevret picture TomDemulierChevret  路  3Comments