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

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

本文介绍了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.

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将解析服务注入组件控制器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:28