如何通过编程方式获取Angular服务 [英] How to get Angular service by name programmatically

查看:85
本文介绍了如何通过编程方式获取Angular服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中包含我需要以编程方式在我的一个控制器中注入的服务名称。

I have a string that contains the name of a service I need to inject into in one of my controllers programmatically.

function Ctrl() {
    var serviceName = '$myService';
    var service = ???
}

我认为应该很容易做类似的事情:

I am assuming it should be pretty easy to do something similar to:

function Ctrl($injector) {
    var serviceName = '$myService';
    var service = $injector.inject(serviceName);
}

我知道我没有正确的语法但有人可以给我正确的语法?

I know I don't have the syntax correct but can someone give me the correct syntax?

推荐答案

你可以得到这样的服务:

You can get a service like this:

var myService = $ injector.get('MyServiceName');

这篇关于如何通过编程方式获取Angular服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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