Angular @ngrx/store

tags: Angular @ngrx/store
  • 首先在app下 創建一個 action 跟 reducer

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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 }}