引入StoreModule时Angular项目编译失败,求助解决NgRx报错
Hey there, I've dealt with this exact problem before—those RxJS-related errors when setting up NgRx are almost always a version mismatch issue. Let's break down what's going on and how to fix it:
What's Causing the Errors?
The error messages (like Module '"...rxjs/BehaviorSubject"' has no exported member 'BehaviorSubject' and Cannot find module 'rxjs-compat/BehaviorSubject') tell us two key things:
- Your Angular project is using RxJS 6+, which restructured how core classes like
ObservableandBehaviorSubjectare imported and distributed. - The version of
@ngrx/storeyou installed is built to work with an older RxJS version (pre-6), so it's looking for the old import paths that no longer exist natively in RxJS 6+.
Fix Options
Option 1: Install rxjs-compat (Quick Temporary Fix)
If you just need to get up and running fast, installing the rxjs-compat package will add backward compatibility for the old RxJS import paths your current NgRx version expects:
yarn add rxjs-compat
Or if you use npm:
npm install rxjs-compat
Note: This is a short-term solution—rxjs-compat is deprecated, so it's better to move to a compatible NgRx version for long-term maintenance.
Option 2: Upgrade NgRx to Match Your RxJS/Angular Version (Recommended)
NgRx maintains strict version compatibility with Angular and RxJS. Here's how to do this properly:
- First, check your project's Angular version (run
ng versionin your terminal) and match it to the corresponding NgRx major version (e.g., Angular 14 ↔ NgRx 14, Angular 15 ↔ NgRx 15, etc.). - Upgrade NgRx Store to the compatible version:
# For yarn, replace X with your target major version yarn add @ngrx/store@X # Or use ng update for automated dependency handling ng update @ngrx/store - After upgrading, keep using the RxJS 6+ import syntax you already have (like
import { Observable } from 'rxjs';—that's correct!).
Additional Troubleshooting Steps
If the above fixes don't work, try these cleanup steps to eliminate caching issues:
- Delete your
node_modulesfolder - Delete your
yarn.lock(orpackage-lock.jsonif using npm) - Reinstall dependencies with
yarn installornpm install - Double-check your
app.module.tsimport setup to ensure it's correct:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { StoreModule } from '@ngrx/store'; import { rootReducer } from './state/app.reducer'; // Your root reducer @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, StoreModule.forRoot({ state: rootReducer }) // Replace with your reducer configuration ], bootstrap: [AppComponent] }) export class AppModule { }
内容的提问来源于stack exchange,提问作者SrgSprinkles

