Home > Net >  How to use NGXS Select() in an angular component
How to use NGXS Select() in an angular component

Time:03-18

I've an angular project with NGXS that I just setup.

In my AuthState, I've the following:

@Injectable()
export class AuthState {
  @Selector()
  static isAuthenticated(state: AuthStateModel) {
    return state.currentUser !== null;
  }
  //...
}

In a component, I'm doing the following:

export class HeaderComponent implements OnInit {
  @Select(AuthState.isAuthenticated) isAuthenticated$: Observable<boolean>;
  //...
}

But it gives me a compilation error:

src/app/layout/header/header.component.ts:14:38 - error TS2564: Property 'isAuthenticated$' has no initializer and is not definitely assigned in the constructor.

14   @Select(AuthState.isAuthenticated) isAuthenticated$: Observable<boolean>;
                                        ~~~~~~~~~~~~~~~~

I totally understand why, here, angular has no way to know it will be properly initialized.

I've search a bit, and found a lot of link pointing to disable property initialization checks with

"strictPropertyInitialization": false

in the tsconfig.

But the thing is that I like this check, and I don't want to disable it. There has to be a way to not disable this for the whole application but still use NGXS Select's, right?

CodePudding user response:

Since you dont want to change the setting. then you would have to set it via constructor.

constructor(store: Store){
    this.isAuthenticated$= store.select(AuthState.isAuthenticated);
}
  • Related