"推迟undefined"在AngularJS中

时间:2016-02-22 13:26:02

标签: angularjs angularjs-scope

.controller('LoginConnect', ['$scope', 'connecting',
function($scope, connecting){
    $scope.user = {};
    $scope.connect = function($scope, $q){
      connecting();
    };
  }
])
.factory("connecting", [ function($scope,$q, $http){
      var deferred = $q.defer();
      $http({
          method: 'POST',
          url: "http://api.tiime-ae.fr/0.1/request/login.php",
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          transformRequest: function(obj) {
              var str = [];
              for(var p in obj)
              str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
              return str.join("&");
          },
          data: {login: $scope.user.login, password: $scope.user.password}
          })
      .success(function(result){
         deferred.resolve(result);
         var promise = deferred.promise;
         promise.then(function(result){
           jsonTab = angular.fromJson(result);
            $scope.result = result["data"];
        $scope.user.token = result["data"];
          });
        })
      }
    ])

嗨,我是Angular JS的新手,我遇到以下错误:TypeError: Cannot read property 'defer' of undefined

我们如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您为connecting工厂编写了错误的语法。将其更改为:

.factory("connecting", ["$scope", "$q", "$http", function($scope,$q, $http){

您正在使用inline array annotation语法来注入Angular依赖项,因此您需要在上面的列表中命名确切的名称:"$scope", "$q", "$http"。由于您尚未在其中定义任何名称,因此变量$q变为空。

详细了解:https://stackoverflow.com/a/35336414/2405040

答案 1 :(得分:0)

顺便说一下:请不要使用命名参数语法。它更难阅读,更多写作,而且非常好。

做类似的事情:

if(array){
 //return the height of the view from XIB
}else{
 //return the calculated height
}