【发布时间】:2020-03-13 02:34:17
【问题描述】:
我在我的 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 );
})
}
我的日志里什么都没有,你能帮忙吗?
【问题讨论】: