簡體   English   中英

在es5中創建一個角度2服務

[英]create an angular 2 service in es5

我試圖在角度2中創建一個自定義服務,但我似乎無法在es5中找到有關角度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中這樣做?

以下是使用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
  ]);
});

你也可以看看這個問題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM