Angular
@ngrx/store
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);
}
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 {}
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' }));
}
}
{{ appState$ | async }}