如何在angularJs配置中调用服务? [英] How do I call a service in angularJs config?

查看:79
本文介绍了如何在angularJs配置中调用服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在应用程序的配置模块中调用的服务,但是当我尝试注入它时会出错.有任何想法吗?仅供参考-注入和执行此服务后,该服务在控制器中可以正常工作.

I have a service that needs to be called in the app's config module but it errors when I try to inject it. Any ideas? FYI - this service works perfectly fine in controllers when injected and executed.

app.config(['$routeProvider', 'myService', function($routeProvider, myService) {
    var controller = myService.getSomeValue() ? 'FirstController', 'SecondController';
    $routeProvider
        .when('/', {
            'templateUrl': '/myTemplate.html'
            'controller': controller
        })
});

由于以下原因,无法实例化模块应用程序: 错误:[$ injector:unpr] http://errors.angularjs .org/1.5.7/$ injector/unpr?p0 = myService

Failed to instantiate module app due to: Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=myService

推荐答案

AngularJS框架分为两个阶段运行,即配置阶段和运行阶段.在配置阶段只能注入提供者对象.服务只能在运行阶段注入.

The AngularJS framework operates in two phases, the config phase and the run phase. Only provider objects can be injected in the config phase. Services can only be injected during the run phase.

从文档中:

module.config(configFn);

使用此方法通过注入服务的提供者来配置服务>,例如用于将路由添加到 $ routeProvider .

module.config(configFn);

Use this method to configure services by injecting their providers, e.g. for adding routes to the $routeProvider.

请注意,您只能注入提供者常量 插入此函数.

Note that you can only inject providers and constants into this function.

有关如何配置服务的更多信息,请参见提供商食谱.

For more about how to configure services, see Provider Recipe.

有关更多信息,请参见

  • AngularJS module type API Reference - config
  • AngularJS Developer Guide - Providers - Summary

这篇关于如何在angularJs配置中调用服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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