Angular和RxJS导入 [英] Angular and RxJS imports

查看:770
本文介绍了Angular和RxJS导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是知道分别导入我的 Observable 运算符来限制加载时间。但是我今天注意到了一些事情,我希望有人可以向我解释。

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.

我正在使用带Webpack的IntelliJ / WebStorm。

I am using IntelliJ/WebStorm with Webpack.

我们在 ngOnInit 的页面上说我有一个http电话:

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';

全世界都很好。直到我需要使用Observable。所以,我将添加一个。

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);
 }

现在编译器可以理解地抱怨它找不到Observable,所以我得到了IntelliJ / WebStorm为我导入它并将其添加到我的文件顶部:

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';

一切都好了。但是,这个新的导入似乎使地图导入无关紧要。我的意思是,如果我删除地图导入并且只保留一个Observable,则所有编译都很好......

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...

但是,如果我指定导入Observable就像这个:

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...

我导入我的Observable时是否导入了所有RxJS?

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

import {Observable} from 'rxjs';

如果是这样,我如何告诉IntelliJ不要这样做并仅导入类?

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

推荐答案

为什么没有一个带有所需rxjs可观察类扩展和运算符的文件(例如:rxjs-extensions.ts)?

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';

然后在你的主模块(ex app.module.ts)中从这个文件导入:

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

import './rxjs-extensions';

在主要组件中(例如:app.component.ts)只需导入Observavle:

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.

这篇关于Angular和RxJS导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆