# Angular @ngrx/store ###### tags: `Angular` `@ngrx/store` * 首先在app下 創建一個 action 跟 reducer ![](https://i.imgur.com/AyYE80C.png) > root-action.ts ``` import { createAction, props } from '@ngrx/store'; export const changeAuth = createAction('ChangeAuth', props<{ auth: string }>()); ``` > root-reducer.ts ``` import { Action, createReducer, on } from '@ngrx/store'; import { changeAuth } from './root-action'; export interface State { auth: string; } export const initialState: State = { auth: 'user', }; const _changeAuthReducer = createReducer( initialState, on(changeAuth, (state, { auth }) => ({ auth })) ); export function changeAuthReducer(state, action) { return _changeAuthReducer(state, action); } ``` * 匯入 app.module.ts ``` import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { StoreModule } from '@ngrx/store'; import { changeAuthReducer } from './store/root-reducer'; @NgModule({ declarations: [AppComponent], imports: [ StoreModule.forRoot({ appState: changeAuthReducer }), StoreDevtoolsModule.instrument(), ], providers: [{ provide: NZ_I18N, useValue: zh_TW }], bootstrap: [AppComponent], }) export class AppModule {} ``` * 在需要用到的component上匯入 > app.component.ts ``` import { Component } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { changeAuth } from './store/root-action'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { appState$: Observable<{ auth: string }>; constructor(private store: private store: Store<{ appState }>) { this.appState$ = store.pipe(select('appState')); this.appState$.subscribe((val) => { console.log(val); }); } changeAuth() { this.store.dispatch(changeAuth({ auth: 'user' })); } } ``` * html板模上應用必須搭配 async ``` {{ appState$ | async }} ```