javascript - 为 DI 正确定义 Angular 2.1.2 ES5 服务

标签 javascript angular ecmascript-5

我定义了一个 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;

https://github.com/angular/angular/blob/2.0.0-beta.5/modules/angular2/src/core/util/decorators.ts#L247-L267

现在您只需使用 ng.core.Class 即可为您的服务提供服务。这是备忘单

这是 Plunker Example

关于javascript - 为 DI 正确定义 Angular 2.1.2 ES5 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467886/

相关文章:

javascript - 如何使用javascript检查多维对象中是否存在值

javascript - React 条件返回中预期的属性分配

javascript - 如果图像未正确加载,如何显示默认图像?

angular - Azure Web 应用程序 Angular 5 + dotnet core 2.1 部署后刷新

javascript - Nodejs 4.x 上的 ES6 代码 : Is V8 4. 5 直接运行 ES6 的原生 JS 引擎?

javascript - 函数引用其属性的 javascript (ECMAScript) 是否合法?

javascript - 如果 React 组件库需要 React 作为对等依赖项,我该如何使用它来制作 Preact?

angular - 如何在 Angular 2 测试中对 fixture.whenStable 使用 await

angular - 错误 : StaticInjectorError(DynamicTestModule)[NotificationsComponent

javascript - 访问 Angular2 JavaScript ES5 组件中的元素