2016-08-02 94 views
2

我嘗試在Angular 2(帶有TypeScript的RC 1)Web應用程序中將xml2js用作XML解析器。但是,我只是得到一些錯誤,沒有工作解決方案。在Angular 2中使用JS庫xml2js

這裏是我做的一步一步:通過tsd install xml2js

  • 包含的腳本鏈接到我的index.html通過npm install xml2js
  • 根據d.ts文件安裝

    • 安裝xml2js:<script src="../node_modules/xml2js/lib/xml2js.js"></script>
    • 配置了SystemJS,將'xml2js': '../node_modules/xml2js'添加到了映射中,'xml2js': { defaultExtension: 'js' }添加到了包中
    • import my XML中的xml2js解析器onent通過import {Parser} from 'xml2js';
    • 嘗試在組件的構造函數中使用它:
      var parser = new Parser(); var xml = "<root>Hello xml2js!</root>" parser.parseString(xml, function (err, result) { console.dir(result); });

    這是打開一個網頁包含的組件時,什麼瀏覽器控制檯告訴我:

    module.js:440 Uncaught Error: Cannot find module 'sax'

    GET file:///C:/xxx/source/node_modules/xml2js net::ERR_FILE_NOT_FOUND

    以及

    index.html:17 Error: Error: XHR error loading file:///C:/xxx/source/node_modules/xml2js
    at ZoneDelegate.invokeTask (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:356:38)
    at Zone.runTask (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:256:48)
    at XMLHttpRequest.ZoneTask.invoke (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:423:34)
    Error loading file:///C:/xxx/source/node_modules/xml2js as "xml2js" from file:///C:/xxx/source/frontend/angular/components/mycomponent/mycomponent.js

    「sax」位於node_modules/xml2js/node_modules/sax,通過npm安裝。 我錯過了安裝外部庫的情況?有沒有一種「更好」的方式來使用外部JS庫與Angular 2 & TypeScript?

  • +0

    相同。最終它抱怨它無法找到「事件」或「計時器」,並不知道如何處理這個問題。 – sss4r

    回答

    2

    是的,還有更好的辦法。

    您可以使用System.set('xml2js', System.newModule(require('xml2js')))在systemjs中加載本地xml2js模塊。

    對於現場演示,您可以訪問我的Github Repo

    +0

    非常感謝!這是一個很好的工作,簡單的解決方案。 – fr31b3u73r

    +0

    不幸的是,當我嘗試這個時,我在控制檯中看到一個ReferenceError:無法找到變量require。 – sss4r

    +0

    @ sss4r對不起,我不知道它爲什麼會發生。信息太少。 –