create an angular 2 service in es5

爱⌒轻易说出口 提交于 2019-12-01 00:00:25
Thierry Templier

Here is a complete sample of dependency injection with ES5. (service into component, service into service). Don't forget to specify your service when bootstrapping your application or within the providers attribute of components.

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
  ]);
});

In your case, I think that your forgot to add app.database in providers. Something like:

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

You could also have a look at this question:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!