我定义了一个 Angular 2 服务,其中注入(inject)了 Http 服务并由其他组件使用,但我认为我做得不正确:
(function (app) {
'use strict';
app.LoaderService = ng.core.Component({
providers: [ng.http.Http],
// TODO We shouldn't need to define a template in a service. Maybe service shouldn't be a Component?
template: ''
}).Class({
constructor: [ng.http.Http, function (http) {
this.http = http;
}],
getData: function (url, target) {
var getter = this.http.get(url);
getter.subscribe(function (result) {
target.data = result.json();
});
}
});
})(window.app || (window.app = {}));
虽然这有效,但使用“ng.core.Component”强制我定义一个"template",否则我会收到“未指定模板”错误,但它实际上只是一个服务,它不需要模板。
我尝试使用“ng.core.Injectable().Class(...)”定义它,如这个问题所示:
create an angular 2 service in es5
但这给出了错误“ng.core.Injectable(...).Class is not a function”。也许 Angular 自从写完这个答案后已经发生了变化?
还有很多将服务编写为简单函数的示例,但这不允许我将 Http 服务注入(inject)其中。
我应该如何在纯 Javascript 中定义服务以支持将 Http 注入(inject)其中并允许将其注入(inject)到组件中?
最佳答案
是的,不再有 Class
属性。
ng2 beta-5 的源代码如下所示:
TypeDecorator.annotations = chainAnnotation;
TypeDecorator.Class = Class;
if (chainFn) chainFn(TypeDecorator);
return TypeDecorator;
现在您只需使用 ng.core.Class
即可为您的服务提供服务。这是备忘单
关于javascript - 为 DI 正确定义 Angular 2.1.2 ES5 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467886/