Angular and RxJS imports

2019-02-08 18:40发布

I've always known to import my Observable operators separately to limit the load times. However I've noticed something today that I hope someone could please explain to me.

I am using IntelliJ/WebStorm with Webpack.

Let's say on a page in my ngOnInit I have an http call:

 ngOnInit() {  
        this.http.get('https//:google.com').map(e => e);
 }

If I don't import the map operator the compiler will complain, so I import it like this:

import 'rxjs/add/operator/map';

All is good in the world. Until I need to use an Observable. So, I'll add one.

 ngOnInit() {
        let test = Observable.create(subscriber => {
            return null;
        });

        this.http.get('https//:google.com').map(e => e);
 }

Now the compiler understandably complains that it cannot find Observable, so I get IntelliJ/WebStorm to import it for me and adds this at the top of my file:

import {Observable} from 'rxjs';

All is good again. But, this new import seems to make the map import irrelevant. What I mean is that, if I remove the map import and just leave the Observable one in, all compiles fine...

However, if I specify to import Observable like this:

import {Observable} from 'rxjs/Observable';

Then I must re-add the import for the map operator...

Am I importing all of RxJS when I import my Observable like this?

import {Observable} from 'rxjs';

If so, how can I tell IntelliJ to not do that and import class only?

3条回答
在下西门庆
2楼-- · 2019-02-08 18:43

Starting from WebStorm 2016.3 (I believe), you have an option to blacklist certain imports. Editor > Code Style > StypeScript

Do not import exactly from: [rxjs]

Additionally, there is a flag available in tslint to prohibit global imports:

{
  "rules": {
    "import-blacklist": [true, "rxjs"]
  }
}
查看更多
霸刀☆藐视天下
3楼-- · 2019-02-08 18:44

Why not have a file(ex: rxjs-extensions.ts) with your required rxjs observable class extensions and operators?

// Observable class extensions
import 'rxjs/add/observable/throw';

// Observable operators
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';

And then in your main module (ex app.module.ts) import from this file:

import './rxjs-extensions';

And in your main component (ex: app.component.ts) just import Observavle:

import { Observable } from 'rxjs/Rx';

This is how it is covered on the main angular tutorial.

查看更多
别忘想泡老子
4楼-- · 2019-02-08 18:50

You can use all operators by using this:

import * as Rx from "rxjs/Rx";

Rx.Observable.of(1,2,3,4,5);
查看更多
登录 后发表回答