在迁移到库时,Angular应用的状态可能会变得复杂。不同的库之间可能会共享一个状态,而这些库的状态也可能会影响到主应用程序本身的状态。为了解决状态管理的问题,我们可以使用 NgRx Redux 库。
以下是一个使用 NgRx 实现状态管理的示例:
interface FeatureState {
feature: FeatureState;
}
interface AppState {
feature: FeatureState;
}
import { Action } from '@ngrx/store';
export const ADD_TODO = '[Todo] Add Todo';
export class AddTodo implements Action {
readonly type = ADD_TODO;
constructor(public payload: any) {}
}
export type All = AddTodo;
import { ADD_TODO, All } from './actions';
export const initialState = {
todos: [] as any[]
};
export function reducer(state = initialState, action: All) {
switch (action.type) {
case ADD_TODO: {
return {
...state, todos: [...state.todos, action.payload]
};
}
default:
return state;
}
}
import { StoreModule } from '@ngrx/store';
import { reducer } from './reducers';
@NgModule({
imports: [
BrowserModule,
StoreModule.forRoot({
feature: reducer
})
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Store } from '@ngrx/store';
import { AddTodo } from '../actions';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent {
todos: Observable;
constructor(private store: Store) {
this.todos = store.select(state => state.feature.todos);
}
addTodo() {
this.store.dispatch(new AddTodo({
id: Date.now(),
text: 'New Todo'
}));
}
}
通过使用 NgRx Redux 库,我们可以更好地
上一篇:Angular-嵌套API调用