Angular 2与NgRx
创始人
2024-10-15 17:02:21
0

要解决Angular 2与NgRx的问题,可以按照以下步骤进行:

  1. 首先,确保您已经安装了Angular CLI,并使用它创建了一个新的Angular项目。您可以使用以下命令安装Angular CLI:
npm install -g @angular/cli

然后,使用以下命令创建一个新的Angular项目:

ng new my-project
  1. 安装NgRx库。在项目文件夹中运行以下命令:
npm install --save @ngrx/store
  1. 创建一个新的Action。在项目文件夹中创建一个名为counter.actions.ts的新文件,并添加以下内容:
import { createAction, props } from '@ngrx/store';

export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');
  1. 创建一个新的Reducer。在项目文件夹中创建一个名为counter.reducer.ts的新文件,并添加以下内容:
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';

export const initialState = 0;

export const counterReducer = createReducer(
  initialState,
  on(increment, (state) => state + 1),
  on(decrement, (state) => state - 1),
  on(reset, () => initialState)
);
  1. 在主模块中注册Reducer。打开app.module.ts文件,并添加以下内容:
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ count: counterReducer })
  ],
  // ...
})
export class AppModule { }
  1. 在组件中使用Store。打开app.component.ts文件,并添加以下内容:
import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';

@Component({
  selector: 'app-root',
  template: `
    
    
Current Count: {{ count$ | async }}
`, }) export class AppComponent { count$ = this.store.pipe(select('count')); constructor(private store: Store<{ count: number }>) {} increment() { this.store.dispatch(increment()); } decrement() { this.store.dispatch(decrement()); } reset() { this.store.dispatch(reset()); } }
  1. 运行应用程序。使用以下命令在浏览器中启动应用程序:
ng serve

这样,您就可以在浏览器中看到一个简单的计数器,并使用NgRx进行状态管理。点击按钮时,计数器的值会增加、减少或重置。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...