【问题标题】:Angular2 http is missing .map function [duplicate]Angular2 http缺少.map函数[重复]
【发布时间】:2016-04-07 11:51:50
【问题描述】:

我在tutorial 中找到了这个示例代码:

getRandomQuote() {
  this.http.get('http://localhost:3001/api/random-quote')
    .map(res => res.text())
    .subscribe(
      data => this.randomQuote = data,
      err => this.logError(err),
      () => console.log('Random Quote Complete')
    );
}

但是当我尝试使用它时,我只得到TypeError: this.http.get(...).map is not a function in [null]

getChannels():Promise<Channel> {
    return this.http.get('...')
        .map(function (response:Response) {
            ...
        }).toPromise();
}

我的 Typescript 编译器告诉我这些方法是可用的,但是在检查 http.get() 的返回值时它们丢失了。

我使用了当前angualar2入门指南的package.json:

"dependencies": {
  "angular2": "2.0.0-beta.0",
  "systemjs": "0.19.6",
  "es6-promise": "^3.0.2",
  "es6-shim": "^0.33.3",
  "reflect-metadata": "0.1.2",
  "rxjs": "5.0.0-beta.0",
  "zone.js": "0.5.10"
},

...

<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>

有什么想法我现在可能会出错吗?

【问题讨论】:

标签: typescript angular


【解决方案1】:

Observable 默认只带有几个运算符。您必须明确导入它们:

import 'rxjs/add/operator/map';

或者,如果您不想考虑,只需加载所有内容(例如,在您的引导文件中):

import 'rxjs/Rx';

【讨论】:

  • 这应该是公认的答案。更短、更容易摸索和工作。
  • 我不知道为什么但是我需要添加import * as Rx from 'rxjs';Rx.Observable.of(0);来使Observable支持地图功能
  • 这实际上是一个非常糟糕的解决方案@tom10271。永远不要使用 import *
  • @Enrico 我没有说并建议这是一个解决方案,我绝对知道 import *.我只是说我很困惑为什么这是我项目中的工作。
【解决方案2】:

您会希望您的 index.html 看起来像这样,以便 system.js 可以找到您在组件中导入的所有 rxjs 依赖项。

        <script src="/lib/anguar2/angular2-polyfills.js"></script>
        <script src="/lib/es6-shim/es6-shim.js"></script>
        <script src="/lib/systemjs/system.src.js"></script>

        <script>
            System.config({
                defaultJSExtensions: true,
                packages: {
                    app: {
                        format: 'register'
                    }
                },
                map: {
                    'rxjs':"lib/rxjs"

                }
            });
        </script>
        <script src="/lib/anguar2/angular2.dev.js"></script>
        <script src="/lib/anguar2/router.dev.js"></script>
        <script src="/lib/anguar2/http.js"></script>
        <script>
            System.import('app/boot');
        </script>
确保“lib/rxjs”文件夹包含 node_modules/rxjs 文件夹中的所有文件。并非所有这些都将被加载,只有您需要的那些及其依赖项(system.js 会为您解决)。

现在您可以在 boot.ts 文件中使用它:

import 'rxjs/add/operator/map';

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 2016-05-01
    • 2016-04-16
    • 2016-05-09
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多