create an angular 2 service in es5

后端 未结 1 818
醉酒成梦
醉酒成梦 2021-01-06 12:27

Im trying to create a custom service in angular 2 but i can\'t seem to find any documentation on angular 2 services in es5 (which is what im writing my code in) i\'ve tried

相关标签:
1条回答
  • 2021-01-06 12:44

    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:

    • Dependency Injection in Angular 2 with ES5
    0 讨论(0)
提交回复
热议问题