在 angular 2 服务中加载动态服务
Loading dynamic service inside angular 2 service
我正在尝试做一种套接字处理程序。所以在我的 angular 2 代码中,我得到了一个名为 "socket.service.ts".
的服务
此服务导入套接字 io 库并创建套接字。
但我正在尝试从 json 文件中获取不同的处理程序。
例如 :
用户编辑 config.json 文件中的 "handler" 键,它应该更改套接字的处理程序。
我希望此处理程序具有 angular 2 服务语法。所以我尝试使用
导入这个动态服务
System.import(path).then()
但它给了我一个错误。
这是我的 socket.service :
private _byHandler() {
var _this = this;
this._initHandler((socketHandler) => {
_this.config = socketHandler.getConfig(_this.config);
_this._handler = socketHandler;
_this._createSocket();
});
}
private _initHandler(callback) {
let _this = this,
handler = this.config.handler,
path = "./../handlers/socket/" + handler + "/" + handler + "handler";
System.import(path).then(callback);
}
谢谢!
好的,我找到了解决方案:
首先,我的路径变量不好,我们应该知道 System.import 的值 return 不是 class 本身,而是一个包含 class 的对象。
所以在 .then() 中应该做类似的事情:
let handlerClass = null;
for(let k in socketHandler) {
handlerClass = k; //Get the first key of the object cause we don't know the class name
break;
}
_this._handler = new socketHandler[handlerClass]();
我正在尝试做一种套接字处理程序。所以在我的 angular 2 代码中,我得到了一个名为 "socket.service.ts".
的服务此服务导入套接字 io 库并创建套接字。
但我正在尝试从 json 文件中获取不同的处理程序。 例如 : 用户编辑 config.json 文件中的 "handler" 键,它应该更改套接字的处理程序。
我希望此处理程序具有 angular 2 服务语法。所以我尝试使用
导入这个动态服务System.import(path).then()
但它给了我一个错误。
这是我的 socket.service :
private _byHandler() {
var _this = this;
this._initHandler((socketHandler) => {
_this.config = socketHandler.getConfig(_this.config);
_this._handler = socketHandler;
_this._createSocket();
});
}
private _initHandler(callback) {
let _this = this,
handler = this.config.handler,
path = "./../handlers/socket/" + handler + "/" + handler + "handler";
System.import(path).then(callback);
}
谢谢!
好的,我找到了解决方案: 首先,我的路径变量不好,我们应该知道 System.import 的值 return 不是 class 本身,而是一个包含 class 的对象。
所以在 .then() 中应该做类似的事情:
let handlerClass = null;
for(let k in socketHandler) {
handlerClass = k; //Get the first key of the object cause we don't know the class name
break;
}
_this._handler = new socketHandler[handlerClass]();