Ember将服务注入Ember Utility [英] Ember Inject Service into Ember Utility

查看:72
本文介绍了Ember将服务注入Ember Utility的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Ember有一个记录器,但是我想创建自己的记录器以供学习。我有一个称为logger的服务,并且我希望能够在任何地方使用此服务。我将这个服务注入到组件,控制器等中没有问题。我不想在创建实用程序的任何地方都传递记录器。当我尝试将其注入对象时,它抱怨不在容器中。最好的方法是什么?

I know Ember has a logger, but I wanted to create my own for learning purposes. I have a service called logger, and I want to be able to use this service everywhere. I have no problem injecting this service into components, controllers, and etc... I cannot figure out how to inject this service into a Utility I created without passing it through the create function. I don't want to have to pass my logger everywhere I create the utility. When I try to inject it into the object it complains about not being in a container. What's the best way to do this?

推荐答案

好吧,了解 Ember.inject是很重要的。服务实际上是确实!像这样的简短版本:

Okay, its important to understand what Ember.inject.service actually does! Its like a shorter version for this:

myService: Ember.computed({
  get() {
    return Ember.getOwner(this).lookup('service:myService);
  }
}),

那么这 getOwner 是什么?它为您提供对象的所有者。您的大多数对象(例如模型,控制器,组件,视图等)都是由依赖注入(DI)容器创建的。为了使类在DI容器上可用,需要已注册

So what is this getOwner? It gives you the owner of an Object. Most of your objects like models, controllers, components, views and so on are created by the Dependency Injection (DI) container. For a class to be available on the DI container it needs to be registered.

您的默认类(如控制器,路线,视图)由Resolver自动注册。注册后,您可以将它们自动创建,将它们自动注入到其他类中。容器。

Your default classes like controllers, routes, views are automatically registered by the Resolver. After registration you can inject them into other classes automatically when they are created by the container. Also into all instances created by the container the owner is injected.

由于容器本身是私有的,因此这些公共API位于应用程序上。

getOwner还返回该应用程序。

Because the container itself is private, these public APIs are on the Application. getOwner also returns the application.

如果要在容器上手动查找实例,可以使用查找

If you want to manually lookup an instance on the container you can use lookup.

对于您的实用程序类,您可能使用普通的 .create()来获取对象。当然,这不会自动将其耦合到您的应用程序,因此所有者不可用。自动注入也将不起作用。

For your utility class you probably use a normal .create() to get the object. This of course will not automatically couple it to your application, so the owner is not available. Also automatic injection will not work.

您可以使用 ownerInjection

myClass.create(Ember.getOwner(this).ownerInjection(), {...});

然后 Ember.inject.service 将起作用

您可以做的另一件事是在容器上注册实用程序对象,然后查找它们。然后会自动注入所有者。

The other thing you could do is to register your utility objects on the container and then look them up. Then the owner is automatically injected.

这篇关于Ember将服务注入Ember Utility的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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