在 es5 中创建一个 angular 2 服务
create an angular 2 service in es5
我正在尝试在 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 中执行此操作?
这是一个完整的 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
]);
});
你也可以看看这个问题:
- Dependency Injection in Angular 2 with ES5
我正在尝试在 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 中执行此操作?
这是一个完整的 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
]);
});
你也可以看看这个问题:
- Dependency Injection in Angular 2 with ES5