繁体   English   中英

在Angularjs中将服务/常量注入提供者

[英]Injecting services/constants into provider in Angularjs

这里的问题是我能够访问getRoutes(),但我无法访问注入的常量 - “配置”。 我错过了什么? 谢谢。

(function () {
    'use strict';

    var app = angular.module('app');

    app.constant('configuration', {
       PARTIAL_PATH: "/app/components/partials"
    });

    app.module('app', [
        'routeService'
    ]);

    var routeServiceModule = angular.module('routeService', ['common']);

    routeServiceModule.provider('routeConfig',function () {

    this.getRoutes = function () {
        return [
            {
                url: '/login',
                config: {
                    title: 'admin',
                    templateUrl: 'app/components/login/login.html'
                }
            }, {
                url: '/',
                config: {
                    templateUrl: 'app/components/dashboard/dashboard.html',
                    title: 'Dashboard'
                }
            }
        ];
    };

    this.$get = ['configuration', function (configuration) {

        var service = {
            getRoutes: getRoutes(),
            configuration: configuration.PARTIAL_PATH
        };

        return service;
    }];

app.config(['$routeProvider', 'routeConfigProvider', function ($routeProvider, routeConfigProvider) {
        //Unable to get the configuration value
        console.log(routeConfigProvider.configuration);
       //Console is returning as "undefined"
        routeConfigProvider.getRoutes().forEach(function(r) {
            $routeProvider.when(r.url, r.config);
        });
        $routeProvider.otherwise({ redirectTo: '/' });
    }
]);
})();

创建了一个plunkr演示: http ://plnkr.co/edit/2TIqgxMxBJEPbnk2Wk6D?p=preview

我想你可能会让路线变得复杂。 你可能有一个很好的理由但是我不知道它可能我建议用这样的东西保持简单:

MyApp.config(function ($routeProvider) {
    $routeProvider.when('/home', {
        templateUrl: 'home.html',
        controller: 'HomeController',
        activeTab: 'home'
    })
};

MyApp.controller('HomeController', function ($route) {
    console.log($route.current.activeTab);
});

我有兴趣知道为什么你可能无法使用这种路由模式或故意选择不同的东西。

(关于你的最后评论,与plnkr)

结果是预料之中的。

在配置时(在app.config()内),您可以访问原始提供程序,如您所定义的那样,它允许您调用“私有”方法或字段(testItem1)并将其配置为运行时使用。 “私有”,因为它们在运行时无法访问。

在运行时(在app.run()和应用程序的其余部分中),当您要求为您编写提供程序的依赖项时,角度注入器会向您提供提供程序的$ get方法的结果,而不是提供程序本身,所以你不能访问“私人”功能。

这个页面是我的启蒙之路: AngularJS:服务与提供商vs工厂

我认为这与您创建初始模块的方式有关。 尝试这个:

    var app = angular.module('app', []);

    app.constant('configuration', {
       PARTIAL_PATH: "/app/components/partials"
    });

    var routeServiceModule = angular.module('routeService', ['app']);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM