我试图在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={}));
但是,当我将其注入到我的组件中时,它将引发错误,没有提供class0的提供程序(class10-> class0),我似乎无法弄清楚如何创建自定义服务.有谁知道如何在es5中做到这一点?
解决方法:
这是ES5依赖项注入的完整示例. (服务成组件,服务成服务).在引导应用程序时或在组件的provider属性内,不要忘记指定服务.
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。