Angular报错:不存在导出成员‘Observable’及模块找不到问题求助
It looks like you’re running into issues with outdated RxJS import syntax—this is super common when working with newer Angular versions that use RxJS 6+. Let’s get those errors sorted out:
Step 1: Update Your Import Statements
In RxJS 6+, core types like Observable and creation functions like of are imported directly from the main rxjs package, not from subpaths like rxjs/Observable or rxjs/observable/of. Replace your current imports with these:
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; // Import both from the main rxjs module import { Hero } from './hero'; import { HEROES } from './mock-heroes';
Step 2: Clean Up Unnecessary Dependencies (If Needed)
The error mentioning rxjs-compat/Observable suggests your project might be trying to use a compatibility layer for older RxJS versions. If you don’t need to support legacy code, uninstall rxjs-compat to eliminate that error:
npm uninstall rxjs-compat
Corrected Full Service Code
Here’s your complete working service with all fixes applied:
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; @Injectable({ providedIn: 'root' }) export class HeroService { constructor() { } getHeroes(): Observable<Hero[]> { return of(HEROES); } }
Why This Fixes the Errors
- RxJS 6+ simplified its import structure to reduce bundle sizes and improve consistency. All core observables and creation operators now live directly in the main
rxjsmodule. - The old subpath imports (like
rxjs/Observable) were deprecated and removed in newer versions, which caused the "Cannot find module" and "no exported member" errors you’re seeing.
内容的提问来源于stack exchange,提问作者Thomas Lee

