Post方法angular JS

时间:2016-02-23 10:26:49

标签: angularjs angularjs-scope

.controller('LoginConnect', ['$scope', 'connecting',
function(connecting, $scope){
    $scope.user = {};
    var inputLogin = $scope.user.login;
    var inputPassword = $scope.user.password;
    $scope.connect = function (){
      connecting(ConnectingFactory);
    };
  }
])
.factory('connecting', ['$http','$q', function ($http,$q,inputLogin, inputPassword, ConnectingFactory){
var ConnectingFactory = {};
console.log(ConnectingFactory);
ConnectingFactory.login = function(){
       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: inputLogin, password: inputPassword}
           })
       .success(function(result){
          deferred.resolve(result);
          var promise = deferred.promise;
          promise.then(function(result){
            console.log(result);
            // jsonTab = angular.fromJson(result);
            //  $scope.result = result["data"];
        //  $scope.user.token = result["data"];
           });
         })
       };


       return ConnectingFactory;

}]);
;

这里是HTML:

    <!-- User Connection  -->
<form name="userConnect" ng-submit="connect()" novalidate ng-controller="LoginConnect">
  <label>
    Enter your name:
    <input type="text"
           name="myEmail"
           ng-model="user.login"
            />
  </label>

    <label>
    Enter your Password:
    <input type="password"
           name="password"
           ng-model="user.password"
            />
  </label>

<input type="submit" value="Connection">
<p>resultat : {{result}}</p>
<p ng-model="user.token">
  token : {{mytoken}}
</p>


<p ng-model="user.datab">
  datas : {{datab}}
</p>
<br><br><br>


</form>

嗨,我是Angular Js开发的新手,我没有错误,但没有任何数据发送到API。我认为他们的功能“connect()”和工厂之间没有联系。你能帮帮我吗?

1 个答案:

答案 0 :(得分:2)

不要使用成功方法。不推荐使用这两种方法。

  

$ http遗留承诺方法成功与错误   弃用。请改用标准方法。如果   $ httpProvider.useLegacyPromiseExtensions设置为false然后这些   方法将抛出$ http / legacy错误。

这是快捷方式

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

这是一个较长的GET方法示例

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Official Documentation

关于工厂,请将其正确称为ConnectingFactory.login()

另外,正如哈利指出的那样,这里的顺序是不正确的。

['$scope', 'connecting',
function(connecting, $scope){