我在我的angular 8项目中安装了ngrx。当我取消操作时,我的商店仍然处于未定义状态
这是我的代码
@NgModule({
declarations: [
AppComponent,
HeadComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
HttpClientModule,
StoreModule.forRoot({ login : Reducer.reducer })
],
providers: [{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true },],
bootstrap: [AppComponent]
还有
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 );
}
这是我触发操作的代码
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);
}));
}
这是我的动作
import { createAction} from "@ngrx/store";
export const LOGIN = createAction('LOGIN');
export const LOGOUT = createAction( 'LOGOUT' );
触发注销操作后,我可以看到状态为
的控制台日志{已记录:0}
但是当我订阅
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 );
})
}
我的日志中什么都没有,请您能帮忙吗?
答案 0 :(得分:1)
已记录在全局存储状态中不存在,但是它是login
的属性(这是您使用StoreModule.forRoot
定义的方式),因此您必须执行以下操作:
store.pipe(select('login', 'logged')).subscribe( elem => { console.log( elem )})
您还将从reducer中获得一个返回值:
return loginReducer( state, action );