I have ngrx install on my angular 8 project. and when i dispacth action my store stay sill undefined
here is my code
@NgModule({
declarations: [
AppComponent,
HeadComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
HttpClientModule,
StoreModule.forRoot({ login : Reducer.reducer })
],
providers: [{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true },],
bootstrap: [AppComponent]
And
export const initialState: State = {
logged : null
};
const loginReducer = createReducer(
initialState,
on(LoginAction.LOGIN, (state) => ({ ...state , logged : 1 })),
on(LoginAction.LOGOUT , (state) => { console.log(state) ; const ret = { ...state, logged : 0 } ; console.log( ret ); return ret })
)
export function reducer(state: State, action : Action) {
loginReducer( state, action );
}
Here is the code where i trigger the action
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const request = req.clone({ url : environment.endpoint + req.url, setHeaders : {'Authorization':'Bearer '+ this.token.get()}});
return next.handle(request).pipe( catchError((error: HttpErrorResponse, caught: Observable<HttpEvent<any>>) => {
if( error && error.status === 401 ) {
this.store.dispatch(Action.LOGOUT());
}
return throwError(error);
}));
}
here are my action
import { createAction} from "@ngrx/store";
export const LOGIN = createAction('LOGIN');
export const LOGOUT = createAction( 'LOGOUT' );
When the logout action is triggered, i can see a console log of my state that is
{ logged: 0 }
But when i subscripe
constructor( private http: HttpClient, private store : Store<Reducer.State>) {
store.pipe(select('logged')).subscribe( elem => { console.log( elem )})
http.get('/api/ping').subscribe(( data ) => {
console.log( data );
})
}
I have got nothing in my log, could you help please ?
Logged does not exist on the global store state, but is a property of login
(this is how you define it with StoreModule.forRoot
), so you will have to do:
store.pipe(select('login', 'logged')).subscribe( elem => { console.log( elem )})
You will also have a return value from the reducer:
return loginReducer( state, action );