【问题标题】:Cannot read property 'post' of undefined angular factory无法读取未定义角度工厂的属性“帖子”
【发布时间】:2016-09-28 12:03:21
【问题描述】:

我被困在一个问题上,我使用 angular 并获得控制器将数据发送到我的工厂,在那里我有方法必须将用户名、登录等发布到我生成 JWT 以供进一步使用的终点,但不知何故我得到了这个错误,甚至不知道为什么会发生。

知道什么可能导致这个问题吗?

TypeError:无法读取未定义的属性“帖子” 在 Object.login (Auth.js:22) 在 Scope.LoginController.$scope.signIn (LoginController.js:11)

这里是我的工厂,用于向我的终点发布请求

'use strict';
angular.module("Diplomka").factory('oauth', [function oauth($http) {
    'use strict';
    return {
        login: function (username, password) {
            var token = "";
            var config = {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                }
            }

            var data = {
                username: username,
                password: password,
                grant_type: "password"
            }

            $http.post("/Token", data, config)
                .then(function (response) {
                    token = response.access_token;
                });
        }
    };
}]);

这是我的控制器

    'use strict';
app.controller('LoginController', ['$scope', 'oauth', '$location', LoginController]);
function LoginController($scope, oauth, $location) {


    $scope.username = "";
    $scope.password = "";

    $scope.signIn = function () {
        oauth.login($scope.username, $scope.password);
    }

};

【问题讨论】:

    标签: angularjs controller jwt factory


    【解决方案1】:

    您的“数组语法”错误。您的服务名称与作为参数传递给工厂构造函数的变量不匹配。

    'use strict';
    angular.module("Diplomka").factory('oauth', ['$rootScope', '$http', function oauth($scope, $http) { // It should be like this
        // Rest of your factory here
    }]);
    

    另外,我认为使用变量名$scope$rootScope 注入您的工厂不是一个好主意。相反,我也将其称为 $rootScope 并替换您工厂中的所有 $scope 引用。

    'use strict';
    angular.module("Diplomka").factory('oauth', ['$rootScope', '$http', function oauth($rootScope, $http) { // It should be like this
        // Rest of your factory here, replacing $scope with $rootScope
    }]);
    

    【讨论】:

    • 哦,我在那里犯了一个多么愚蠢的错误,非常感谢,它现在可以工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2015-08-10
    • 2019-04-28
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多