从'rxjs/Observable'与'rxjs'导入Observable的区别及报错解惑
Hey there! Let me break down exactly why one import worked and the other didn’t—this all boils down to key changes between different RxJS versions.
1. They’re designed for different RxJS versions
import { Observable } from 'rxjs/Observable'
This is the standard import pattern for RxJS 5 and earlier. Back then, theObservableclass and its static creation methods (likeof,from) were split into separate files. To useObservable.of(), you had to explicitly import that static method in addition to the Observable class itself:import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; // Skip this, and you’ll get that error you saw! const myObs = Observable.of(1, 2, 3);Your initial error almost certainly happened because you forgot to add that second import line for the
ofmethod.import { Observable } from 'rxjs'
This is the recommended approach for RxJS 6 and later. RxJS 6 completely overhauled its import structure to make things simpler. The coreObservableclass and all common static creation methods are bundled together in the mainrxjsentry. You can even import creation methods as standalone functions (which is the preferred modern way):import { Observable, of } from 'rxjs'; // Both work, but the second is more idiomatic for RxJS 6+ const obs1 = Observable.of(1, 2, 3); // Legacy-compatible syntax const obs2 = of(1, 2, 3); // Recommended modern syntaxSince this import includes all the necessary bits out of the box, that’s why your code ran without errors once you switched.
2. They affect bundle size differently
- The old
rxjs/Observablepattern let you cherry-pick only the methods you needed, which could keep bundles small—but it required manual management of every single operator/method you used, which was easy to mess up. - RxJS 6+’s unified imports work seamlessly with Tree Shaking (supported by Webpack, Rollup, etc.), so unused code gets automatically stripped out. This keeps bundles lean without the hassle of manual imports.
3. Operator usage differs too (bonus context!)
While not directly related to your error, it’s worth noting:
- In RxJS 5, instance operators (like
map) were imported viaimport 'rxjs/add/operator/map'and chained directly:myObs.map(x => x * 2) - In RxJS 6+, operators are pipeable—you import them from
rxjs/operatorsand use thepipemethod:import { map } from 'rxjs/operators'; myObs.pipe(map(x => x * 2)).subscribe(...);
To sum it up: Your initial error was a mismatch between the old import style and the RxJS version in your project. Stick to import { Observable } from 'rxjs' (and standalone functions like of) for RxJS 6+, and you’ll avoid these headaches.
内容的提问来源于stack exchange,提问作者Sai

