我已经下载了一个用于连接websocket Spring频道的工作简单javascript示例,我正在努力将此功能导入angular 2应用程序。
我已将导入添加到package.json:
"dependencies": {
"@angular/common": "~2.2.1",
(...)
"stompjs": "2.3.3",
"sockjs-client": "1.1.1"
},
然后建议编辑systemjs.config.js:
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
(...)
'sockjs-client': 'npm:sockjs-client',
'stompjs': 'npm:stompjs'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
(...)
'sockjs-client': {
defaultExtension: 'js'
},
stompjs: {
defaultExtension: 'js'
}
}
});
})(this);
但是当我添加导入
时import {Stomp} from "stompjs";
我收到“TS2307:找不到模块”错误消息并将代码编译为:
var stompjs_1 = require("stompjs");
导致http url无效:
http://localhost/myapp/node_modules/stomp-client
而不是JS文件的路径。
我在这里弄错了什么?我搜索了许多SO答案,例如:How to use moment.js library in angular 2 typescript app?我试图做类似的事情。我也尝试了其他导入语法,如:
import * as Stomp from 'stompjs';
但没有任何作用。
如何在Angular2中使用这两个库?
答案 0 :(得分:1)
您需要在systemjs.config.js中编写库中javascript文件的完整路径:
例如,对于stompjs,根据Github上的repo,它可能是:
class DictionaryListViewPseudoBinder : IEnumerable
{
private ListView ListView { get; }
private Dictionary<string,string> Dictionary { get; set; }
public DictionaryListViewPseudoBinder(ListView listView)
{
ListView = listView;
Dictionary = new Dictionary<string, string>();
}
public string this[string key]
{
get
{
return Dictionary.ContainsKey(key) ? Dictionary[key] : "";
}
set
{
if (Dictionary.ContainsKey(key))
{
Dictionary[key] = value;
RepopulateListView();
}
else
{
MessageBox.Show("Dictionary does not contain key " + key + " aborting...");
}
}
}
public void Add(string key, string value)
{
if (!Dictionary.ContainsKey(key))
{
Dictionary.Add(key, value);
RepopulateListView();
}
else
{
MessageBox.Show(string.Format("The Entry \"{0}\" already exists in {1}",key,ListView.Name));
}
}
public void Remove(string key)
{
if (Dictionary.ContainsKey(key))
{
Dictionary.Remove(key);
}
}
public bool ContainsKey(string key)
{
return Dictionary.ContainsKey(key);
}
public bool ContainsKVP(KeyValuePair<string, string> kvp)
{
if (!Dictionary.ContainsKey(kvp.Key))
{
return false;
}
else
{
return Dictionary[kvp.Key] == kvp.Value;
}
}
private void RepopulateListView()
{
ListView.Items.Clear();
foreach (KeyValuePair<string, string> kvp in Dictionary)
{
ListView.Items.Add(kvp.Key).SubItems.Add(kvp.Value);
}
}
public IEnumerator GetEnumerator()
{
return Dictionary.GetEnumerator();
}
}
之后,您可以使用以下语法使用您的库:
map {
(...)
'stompjs': 'npm:stompjs/lib/stomp.min.js'
},
packages: {
// Remove stompjs from here, because you already have the full path
}
您仍然会收到错误import * as stomp from 'stompjs';
,但至少它会在您的浏览器中生效。
我希望它有所帮助。