2016-02-27 82 views
2

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

+0

看到http://stackoverflow.com/questions/34532138/how-to-inject -custom-service-to-angular-component-in-plain-es5-javascript –

+0

我無法找到該問題感謝您的參考是否有anisituation你會使用Injector.resoveAndCreate或ng.core.provide? – Binvention

+0

我從來沒有見過'ng.core.Injectable'或'ng.core.Injector'記錄 - 但我是一個angular2 noob:p –

回答

3

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

你也可以看看這個問題:

+0

我遇到一個問題這個。在角度上你可以有一種共享服務,這樣變量可以通過服務在組件2上分享,這是可能的嗎?我的意思是注入器正在工作,但它創建了兩個單獨的相同服務的實例,而不是在兩個構造函數之間共享它。 – Binvention

+0

沒關係,我想通了,當你注入引導程序然後共享它,但是當你使用組件提供程序注入它的唯一實例 – Binvention

+0

是的,這是因爲分層注入器。看到這個問題的更多細節:http://stackoverflow.com/questions/34804298/whats-the-best-way-to-inject-one-service-into-another-in-angular-2-beta/34807397。 –