正确定义Angular 2.1.2 ES5 service for DI
Correctly defining Angular 2.1.2 ES5 service for DI
我已经定义了一个 Angular 2 服务,其中注入了 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',否则我会收到 'No template specified' 错误,但它实际上只是一项服务,不需要模板。
我尝试使用 'ng.core.Injectable().Class(...)' 来定义它,如这个问题:
但这会产生错误 'ng.core.Injectable(...).Class is not a function'。可能 Angular 自该答案写出后发生了变化?
也有很多将服务编写为简单函数的示例,但那不会让我将 Http 服务注入其中。
我应该如何在纯 Javascript 中定义服务以支持将 Http 注入其中并允许将其注入组件?
是的,不再有Class
属性。
ng2 beta-5 的源代码如下所示:
TypeDecorator.annotations = chainAnnotation;
TypeDecorator.Class = Class;
if (chainFn) chainFn(TypeDecorator);
return TypeDecorator;
今天您只需使用 ng.core.Class
即可获得服务。这是备忘单
- https://github.com/angular/angular/blob/2.1.2/modules/%40angular/docs/cheatsheet/class-decorators.md
这里是 Plunker Example
我已经定义了一个 Angular 2 服务,其中注入了 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',否则我会收到 'No template specified' 错误,但它实际上只是一项服务,不需要模板。
我尝试使用 'ng.core.Injectable().Class(...)' 来定义它,如这个问题:
但这会产生错误 'ng.core.Injectable(...).Class is not a function'。可能 Angular 自该答案写出后发生了变化?
也有很多将服务编写为简单函数的示例,但那不会让我将 Http 服务注入其中。
我应该如何在纯 Javascript 中定义服务以支持将 Http 注入其中并允许将其注入组件?
是的,不再有Class
属性。
ng2 beta-5 的源代码如下所示:
TypeDecorator.annotations = chainAnnotation;
TypeDecorator.Class = Class;
if (chainFn) chainFn(TypeDecorator);
return TypeDecorator;
今天您只需使用 ng.core.Class
即可获得服务。这是备忘单
- https://github.com/angular/angular/blob/2.1.2/modules/%40angular/docs/cheatsheet/class-decorators.md
这里是 Plunker Example