在 Angular 中安装 NGRX 11 时,需要确保使用正确的版本和正确的安装方式。以下是解决该问题的步骤:
ng version
如果版本号不是最新的,可以通过以下命令更新:
npm install -g @angular/cli
使用以下命令安装 NGRX 11:
npm install @ngrx/store@11.0.0
如果需要使用其他 NGRX 11 模块,可以将命令替换为相应的模块名称,例如:
npm install @ngrx/effects@11.0.0 npm install @ngrx/router-store@11.0.0
在 app.module.ts 中,导入 NGRX 11 的相关模块,例如:
import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; import { StoreRouterConnectingModule } from '@ngrx/router-store';
@NgModule({ imports: [ BrowserModule, AppRoutingModule, FormsModule, StoreModule.forRoot({}), EffectsModule.forRoot([]), StoreRouterConnectingModule.forRoot(), ], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule {}
在组件中,可以使用 NGRX 的 store、effect 和 selector 等功能。例如,在组件中使用 store 的示例:
import { Component } from '@angular/core'; import { Store } from '@ngrx/store';
@Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { constructor(private store: Store) {}
count$ = this.store.select(state => state.count);
increment() { this.store.dispatch({ type: 'increment' }); } }
通过以上步骤,即可在 Angular 中成功安装和使用 NGRX 11。