我正在按照 ngrx 网站上的教程创建商店/状态,但我无法访问状态属性:
auth.ts
export interface Auth{
email: string;
token: string;
isLoggedIn: boolean;
}
auth.actions.ts
import { createAction, props } from '@ngrx/store';
import {Auth} from '../../models/auth';
export const authenticateUser = createAction('[Login Component] Authtenticate User', props<{payload: Auth}>());
export const logoutUser = createAction('[Navbar Component] Logout User');
auth.reducer.ts
import { Action, createReducer, on } from '@ngrx/store';
import * as AuthActions from '../actions/auth.actions';
export interface State {
email: string;
token: string;
isLoggedIn: boolean;
}
export const initialState: State = {
email: 'test@test',
token: '',
isLoggedIn: false
}
const _authReducer = createReducer(
initialState,
on(AuthActions.authenticateUser, (state, { payload }) => ({
email: payload.email,
token: payload.token,
isLoggedIn: payload.isLoggedIn,
})),
on(AuthActions.logoutUser, state => ({
email: '',
token: '',
isLoggedIn: false,
}))
)
export function authReducer(state: State | undefined, action: Action) {
return _authReducer(state, action);
}
在我的 app.module.ts 中导入
...
import { StoreModule } from '@ngrx/store';
import {authReducer} from './store/reducers/auth.reducer';
imports: [
...
StoreModule.forRoot({ auth: authReducer }),
],
而且我有一个导航栏组件,我想在其中显示用户电子邮件,但是当我尝试在 html 中访问 {{auth.email}} 时出现错误: “标识符‘email’未定义。‘Observable’不包含这样的成员”。 导航栏.component.ts
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Auth } from './../models/auth';
...
auth: Observable<Auth>;
constructor(private store: Store<{auth :Auth}>) {
this.auth = store.select('auth');
}