javascript - AngularJs 在 post 中使用对象

标签 javascript angularjs

我正在尝试将 json 对象传递给我的 factory.login 方法,以便我可以重新使用它。

这是我的代码:

Controller 功能

var data = {email:'test','password':'test'};

vm.login = function() {
            employeeFactory.login(vm.url, vm.data)
                    .then(function(response) {
                        console.log(response);
                    }, function(data)
                    {
                        console.log(data.status);
                    });
        }

工厂

factory.login = function(url,data) {
        return $http({
            'method': 'POST',
            'url': url,
            'data': $.param(
                data
            ),
            'headers': {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
    }
    return factory;

但错误是:

angular.js:13294 TypeError: Cannot read property 'jquery' of undefined
    at Function.n.param (jquery-2.2.2.min.js:4)
    at Object.factory.login (employeeFactory.js:14)
    at employeeController.vm.login (employeeController.js:16)
    at fn (eval at <anonymous> (angular.js:14138), <anonymous>:4:285)
    at b (angular.js:15151)
    at e (angular.js:24674)
    at m.$eval (angular.js:16895)
    at m.$apply (angular.js:16995)
    at HTMLButtonElement.<anonymous> (angular.js:24679)
    at HTMLButtonElement.n.event.dispatch (jquery-2.2.2.min.js:3)

最佳答案

这应该是vm.data

vm.data = {email:'test','password':'test'};

工厂根本不需要 jQuery,只需使用下面的构造即可

factory.login = function(url,data) {
    return $http({
        'method': 'POST',
        'url': url,
         //don't use $.param, as you need jQuery dependency for that
         //for x-www-form-urlencoded you have to use this construction
         //email=test&password=test
        'data': 'email=' + data.email + '&password=' + data.password, 
        'headers': {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
}
return factory;

但考虑在服务器请求处理程序上使用 JSON 类型,因为它更容易

关于javascript - AngularJs 在 post 中使用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36155571/

相关文章:

javascript - 检测 Iframe 内容何时加载(跨浏览器)

angularjs - WYSIWYG Angular 无法添加空格(Text-Angular)

css - AngularJS Material 和 Toastr CSS 不能一起工作

javascript - 监视 AngularJS 中对象的所有属性

javascript - 如何将分辨率与仅针对 IE 11 或更高版本的媒体查询结合起来?

javascript - 使用 jQuery/Javascript 编辑 CSS3 动画

javascript - 如何从 ng-repeat 单个范围更改父范围-Angular JS

AngularJS 等待范围变量从自定义指令评估

javascript - node.js:如何停止已经启动的 http 请求

javascript - JQuery 确定是否所有复选框列表(在 div 中)都已被选中