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

时间:2017-04-05 21:54:39

标签: angularjs webpack angular-routing

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

  

错误:[$ 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);
};

1 个答案:

答案 0 :(得分:-1)

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

<强> 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');
                }]
            }
        })
    }]);
};