将解析服务注入组件控制器的问题

将解析服务注入组件控制器的问题

本文介绍了ngRoute 将解析服务注入组件控制器的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $routeProvider 的 resolve 属性将服务注入控制器,但在运行它时出现此错误.任何建议都会很棒.提前致谢.

I am trying to inject a service into a controller using the resolve property of $routeProvider but I am getting this error when I run it. Any suggestion would be great. Thanks in advance.

错误:[$injector:unpr] 未知提供者:messageProvider <- message

GitUserService.js

module.exports = function (app) {
    app.factory('GitUser', ['$http', function ($http) {
        return {
            GetGitUser: function (username) {
                return $http.get('https://api.github.com/users/' + username)
                .then(function success(response) {
                    return response.data.login;
                }, function error(response) {
                    return console.log("error");
                });
            }
        };
    }]);
};

route.js

module.exports = function (app) {
    require('../../services/GitUserService')(app);

    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/angularhome', {
            template: '<home></home>',
            resolve: {
                message: ['GitUser', function (GitUser) {
                    return GitUser.GetGitUser('test');
                }]
            }
        })
    }]);
};

HomeController.js

require('./Home.scss');

module.exports = function (app) {
    app.component('home', {
        templateUrl: 'Content/app/components/home/Home.html',
        controller: ['message', HomeController]
    });

    function HomeController(message) {
        this.name = message;
    }
};

index.js

module.exports = function (app) {
    require('./route')(app);
    require('./HomeController')(app);
};

推荐答案

根据回复更新了我的代码,这是修复.

Updated my code based on the responses and this is the fix.

HomeController.js

require('./Home.scss');

module.exports = function (app) {
    app.component('home', {
        templateUrl: 'Content/app/components/home/Home.html',
        controller: HomeController,
        bindings: {
            name: '<'
        }
    });

    function HomeController() {
        this.name = name;
    }
};

route.js

module.exports = function (app) {
    require('../../services/GitUserService')(app);

    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/angularhome', {
            template: '<home name="$resolve.message"></home>',
            resolve: {
                message: ['GitUser', function (GitUser) {
                    return GitUser.GetGitUser('test');
                }]
            }
        })
    }]);
};

这篇关于ngRoute 将解析服务注入组件控制器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 23:37