3

我试图在 Angular 2 中创建自定义服务,但我似乎在 es5 中找不到任何关于 Angular 2 服务的文档(这是我编写代码的内容)我尝试过使用它

(function(app){
    app.database=ng.core.Injectable().Class({
        constructor:[function(){
            this.value="hello world";
        }],
        get:function(){return this.value},
    });
    ng.core.Injector.resolveAndCreate([app.database]);
    ng.core.provide(app.database,{useClass:app.database});
})(window.app||(window.app={}));

但是,当我将它注入到我的组件中时,它会引发错误,no provider for class0 (class10 -> class0)我似乎无法弄清楚如何创建自定义服务。有谁知道如何在 es5 中做到这一点?

4

1 回答 1

4

这是使用 ES5 进行依赖注入的完整示例。(服务到组件,服务到服务)。不要忘记在引导您的应用程序时或在providers组件的属性中指定您的服务。

var OtherService = function() {};
OtherService.prototype.test = function() {
  return 'hello';
};

var Service = ng.core.Injectable().Class({
  constructor: [ OtherService, function (service) {
    this.service = service;
  }],

  test: function() {
    return this.service.test();
  }
});

var AppComponent = ng.core
  .Component({
    selector: 'my-app',
    template: '<div>Test: {{message}}</div>',
  })
  .Class({
    constructor: [Service, function (service) {
      this.message = service.test();
    }],
  });

document.addEventListener('DOMContentLoaded', function () {
  ng.platform.browser.bootstrap(AppComponent, [
    OtherService, Service
  ]);
});

就您而言,我认为您忘记添加app.database提供程序。就像是:

document.addEventListener('DOMContentLoaded', function () {
  ng.platform.browser.bootstrap(AppComponent, [
    app.database
  ]);
});

你也可以看看这个问题:

于 2016-02-28T08:59:33.253 回答