【问题标题】:undefined variable localforage in angular2/typescript projectangular2/typescript 项目中未定义的变量 localforage
【发布时间】:2016-04-04 03:48:59
【问题描述】:

我在将 localForage 添加到我的 angular2-seed 项目(使用类型和 webpack)时遇到问题。我是打字和 angular2 的新手。

使用 typings 命令,我将 Typescript 定义添加到 typings.json

    "localforage": "registry:dt/localforage#0.0.0+20160316155526",

在我添加的vendor.ts 文件中

const localforage:LocalForage = require("localforage");

在我的service.tsfile 中,我的 IDE 可以解析导入并自动完成

import {localforage} from "localforage";

this.store = localforage.createInstance({
  name: "products"
})

但是当我运行应用程序时,导入的 localforage 是undefined

ORIGINAL EXCEPTION: TypeError: Cannot read property 'createInstance' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'createInstance' of undefined
    at new SearchService (eval at <anonymous> (http://localhost:3000/app.bundle.js:36:2), <anonymous>:20:53)
    at eval (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:189:2), <anonymous>:13:47)
    at Injector._instantiate (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:777:27)
    at Injector._instantiateProvider (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:715:25)
    at Injector._new (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:704:21)
    at InjectorInlineStrategy.getObjByKeyId (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:247:33)
    at Injector._getByKeyDefault (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:921:37)
    at Injector._getByKey (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:867:25)
    at Injector._getByDependency (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:853:25)
    at Injector._instantiate (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:743:36)

有什么建议吗,谢谢!

【问题讨论】:

  • 似乎您的 angular2 应用在您的 service..ts 文件中找不到 localforage

标签: typescript angular localforage


【解决方案1】:

您似乎忘记指示 systemjs(因为您使用的是 angular2,我假设它是您的加载器)什么是 localforage 以及从哪里加载它。像这样的东西应该可以解决问题:

System.config({
 .....
  paths: {
    localforage: 'path/to/localforage/dist/localforage'
  }
 .....
});

System.defaultJSExtensions = true;

希望对你有帮助

【讨论】:

【解决方案2】:

类型仅用于编译而不用于运行时。所以你需要在你的入口HTML文件中配置SystemJS:

System.config({
  map: {
    localforage: '/path/to/localforage.js'
  },
  (...)
});

这样你就可以导入 localforage 模块了:

import localforage from 'localforage';

【讨论】:

  • 我目前使用webpack 作为加载器。我的项目基于 github.com/angular/angular2-seed
【解决方案3】:

终于不是脚本加载问题了,但我忘了在vendor.ts中添加export关键字

export const localforage:LocalForage = require("localforage");

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多