在 es5 中创建一个 angular 2 服务 [英] create an angular 2 service in es5

查看:22
本文介绍了在 es5 中创建一个 angular 2 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 angular 2 中创建一个自定义服务,但我似乎无法在 es5 中找到任何关于 angular 2 服务的文档(这是我在其中编写代码的内容)我已经尝试使用这个

Im trying to create a custom service in angular 2 but i can't seem to find any documentation on angular 2 services in es5 (which is what im writing my code in) i've tried using this

(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 中做到这一点?

however when i inject it into my component it throws the error no provider for class0 (class10 -> class0) i can't seem to figure out how to create the custom service. does anyone know how to do this in es5?

推荐答案

这里是一个完整的 ES5 依赖注入示例.(服务到组件,服务到服务).不要忘记在引导应用程序时或在组件的 providers 属性中指定您的服务.

Here is a complete sample of dependency injection with ES5. (service into component, service into service). Don't forget to specify your service when bootstrapping your application or within the providers attribute of components.

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.类似的东西:

In your case, I think that your forgot to add app.database in providers. Something like:

document.addEventListener('DOMContentLoaded', function () {
  ng.platform.browser.bootstrap(AppComponent, [
    app.database
  ]);
});

你也可以看看这个问题:

You could also have a look at this question:

这篇关于在 es5 中创建一个 angular 2 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆