【发布时间】:2017-02-08 18:55:17
【问题描述】:
var someObject = {
func: (http: Http)=>{
// do something
}
}
---------------------------------------------
// somewhere in an ng2 module
function injectServices(theObject){
let services = getServices(theObject.func)
//inject services into theObject
....
}
// return services
function getServices(func: Function){
// get params' type of func
let paramTypes = ...
// get services' singleton
let singletons = ...
return singletons;
}
Reflect 是否提供了这样的方法,以便我可以获取参数的函数类型?我怎样才能得到服务类的单例?
场景是我将采用一个实现下面接口的对象来呈现表单视图,并且我有一些自定义服务应该在运行时注入到 $validator、$parser 和 $formatter。
interface IViewSchema {
"title": String,
"buttons": [
{
"buttonText": String,
"role?": "cancel" | "submit",
"callback?": 'cancel' | 'submit' | Function,
"disabled": String
}
],
"viewTemplate?": String,
"formControls?": [
{
"formTemplate?": String,
"label": String,
"maxLength?": number, // max length of input
"minLength?": number, // min length of input
"hidden?": String, // if hidden is true, hide the form control
"disabled?": String, // if data is editable or not, default true,
"placeholder?": String,
"model?": String,
"$validate?":Function[],
"$parser?": { // parse modal data to view data
"async?": boolean, // default false, run async parser or not
"remote?": { // enabled only when async is true
"url": String, // remote url
"method?": String, // calling method
"headers?": JSON,
"body?": String | JSON
},
"parse?": Function
},
"$formatter?": Function
}
]
}
【问题讨论】:
-
没有。 Angular DI 只注入到类的构造函数中。
-
那有什么方法可以通过 Reflect 获取函数的参数类型??
-
对不起,我不知道。你为什么不把它变成一个类,让 Angular2 来做呢?
-
问题是我正在尝试使用单个模板组件来降低构建新表单组件的复杂性。
-
对我来说听起来很奇怪。为什么
$validator、$parser、$formatter必须是函数而不是IViewSchema的方法。如果将服务注入ViewSchemaImpl,那么所有方法都可以访问服务(ViewSchemaImpl的属性)。
标签: angular typescript