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。 –