Angular2 RxJS 获取“Observable_1.Observable.fromEvent 不是函数"错误 [英] Angular2 RxJS getting 'Observable_1.Observable.fromEvent is not a function' error

查看:17
本文介绍了Angular2 RxJS 获取“Observable_1.Observable.fromEvent 不是函数"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AngularJS 2 Beta 0 并且我正在尝试从窗口对象上的事件创建一个 RxJS Observable.我相信我知道在我的服务中将事件捕获为 Observable 的公式:

I'm using AngularJS 2 Beta 0 and I'm trying to create an RxJS Observable from an event on a window object. I believe I know the formula for capturing the event as an Observable in my service:

var observ = Observable.fromEvent(this.windowHandle, 'hashchange');

问题是,每次我尝试运行此代码时,都会收到一条错误消息,指出fromEvent"不是函数.

The problem is that every time I try run this code, I get an error stating that 'fromEvent' is not a function.

Uncaught EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: Observable_1.Observable.fromEvent is not a function

这对我来说似乎意味着我没有正确处理我的 import,因为 RxJS 没有包含在 Angular 2 的构建中,尽管我的应用程序的其余部分运行正常,对我来说意味着 RxJS 是它应该在的地方.

This seems to imply to me that I'm not handling my import correctly now that RxJS is not included in the build of Angular 2, though the rest of my application functions properly, which to me means that RxJS is where it is supposed to be.

我在服务中的导入如下所示:

My import in the service looks like this:

import {Observable} from 'rxjs/Observable';

虽然我也尝试过使用它(对代码进行适当的更改),但结果相同:

Though I have also tried to use this instead (with the appropriate changes to the code), with the same results:

import {FromEventObservable} from 'rxjs/observable/fromEvent';

我的 Index.html 中有以下配置:

I have the following configuration in my Index.html:

<script>
    System.config({
        map: {
            rxjs: 'node_modules/rxjs'
        },
        packages: {
            'app': {defaultExtension: 'js'},
            'rxjs': {defaultExtension: 'js'}
        }
    });
    System.import('app/app');
</script>

有人能告诉我我做错了什么吗?

Can somebody tell me what I'm doing incorrectly?

推荐答案

绝对不需要一次性导入所有操作符!您刚刚导入了 fromEvent 错误.你可以这样做:

Its definitly not needed to import all operators at once! You just imported fromEvent wrong. You could do it like this:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

除了我已经写过的内容之外:使用 angular 的 AoT 编译器进行 tree-shaking 会根据您导入的内容删除未使用的代码.如果只是从 rxjs/rx 导入一些对象或函数,编译器将无法删除任何内容.始终只导入您需要的东西!

In addititon to what I already wrote: tree-shaking with the AoT-Compiler of angular removes unused code, based on what you import. If you just import some objects or functions from rxjs/rx, the compiler can't remove anything. Always import just, what you need!

这篇关于Angular2 RxJS 获取“Observable_1.Observable.fromEvent 不是函数"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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