如何在Chrome/Firefox开发者工具控制台使用RxJS Observable
Hey there! I totally get the frustration when you're trying to quickly test Observable functions and hit that annoying reference error. Let's get you back up and running in no time.
Why this happens
In the past, some environments might have included RxJS by default, but modern browser dev tools don't load it automatically. So when you try to use Rx in the console, the browser has no clue what you're referring to.
Quick fixes to load RxJS in your current tab
Here are a couple of easy ways to inject RxJS into the page right from the console:
Load the latest RxJS bundle (v7+)
Paste this code into your dev tools console and hit enter:const rxjsScript = document.createElement('script'); rxjsScript.src = 'https://unpkg.com/rxjs@7/dist/bundles/rxjs.umd.min.js'; rxjsScript.onload = () => { // Optional: Map to the old `Rx` namespace if you prefer that syntax window.Rx = rxjs; console.log('RxJS loaded! You can now use Rx.Observable or rxjs.Observable'); }; document.head.appendChild(rxjsScript);Once it loads, you can test code like:
// Using the Rx alias Rx.Observable.of(1,2,3).subscribe(console.log); // Or the native rxjs namespace rxjs.of(1,2,3).subscribe(console.log);Access operators (if needed)
The UMD bundle above already includes all operators, which you can access viaRx.operators(orrxjs.operators):Rx.Observable.of(1,2,3).pipe(Rx.operators.map(x => x * 2)).subscribe(console.log);
Pro tip for frequent testing
If you find yourself doing this often, save the loading script as a code snippet in your dev tools:
- In Chrome: Go to the "Sources" tab → "Snippets" → Right-click → "New snippet" → Paste the code → Save. Next time, just right-click the snippet and run it.
- In Firefox: Go to the "Debugger" tab → "Snippets" → Click "New" → Paste the code → Save. Run it with the play button.
This way you don't have to retype the script every time you want to test RxJS code.
内容的提问来源于stack exchange,提问作者Pac0

