在服务中使用$ inject会出错错误:[$ http:badreq] - Angular JS

时间:2017-02-20 07:21:03

标签: angularjs angularjs-service angularjs-factory angularjs-http angularjs-injector

有一个注册表格。在提交注册表单时,我试图通过角度服务保存数据。它给了我一个错误 错误:[$ http:badreq]

这是我的 register.controller.js

   (function(){
       var app = angular.module('myapp');
       app.controller('RegisterController',RegisterController);

       RegisterController.$inject = ['UserService', '$location','$rootScope'];
           function RegisterController(UserService, $location, $rootScope) {
             var vm = this;
             vm.register = register;
                function register(){
                   UserService.Create(vm.user)
                     .then(function(response)
                     {
                       if(response.success){
                       }else{

                      }
                  });
                }
              };
          })();

以下是 UserService

 (function () {
    'use strict';

    angular
      .module('myapp')
       .factory('UserService', UserService);

     UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
     function UserService($timeout, $filter, $q, $http) {
       var service = {};
       service.Create = Create;
       return service;

       var url='ajax.php';

       function Create(user) {
             $http({
                method: 'post',
                url: url,
                data: user,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
               }).
                success(function(data, status, headers, config) {
                    console.log(data);
                }).
               error(function(data, status, headers, config) {
                      console.log(data);
               });
              }
            }
         })();

代码有什么问题。请帮忙。提前致谢

1 个答案:

答案 0 :(得分:0)

您在定义网址之前使用return service;,因此 $ http 服务未定义,而不是网址。解决方案是在最后一个服务函数中移动return语句,如:

(function () {
'use strict';

angular
  .module('myapp')
   .factory('UserService', UserService);

 UserService.$inject = ['$timeout', '$filter', '$q', '$http'];
 function UserService($timeout, $filter, $q, $http) {
   var service = {};
   service.Create = Create;

   var url='ajax.php';

   function Create(user) {
         $http({
            method: 'post',
            url: url,
            data: user,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
           }).
            success(function(data, status, headers, config) {
                console.log(data);
            }).
           error(function(data, status, headers, config) {
                  console.log(data);
           });
          }

     return service;

        }
     })();