简体   繁体   English

使用 $http (REST) 从表单发布数据

[英]Posting data from a form using $http (REST)

I'm trying to use Angular for CRUD operations, but I'm having some trouble sending POST requests to the server.我正在尝试使用 Angular 进行 CRUD 操作,但是我在向服务器发送 POST 请求时遇到了一些问题。

Here's my controller:这是我的控制器:

angular.module('myModule').controller("ListingCtrl", function($scope, posts) {

    $scope.addProject = function () {
        if (!$scope.title || $scope.title === '') {
            return;
        }
        posts.create({
            title: $scope.title,
            short_description: $scope.short_description
        });
        $scope.title = '';
        $scope.short_description = '';
    };

});

Here's my service:这是我的服务:

angular.module('myModule', [])
.factory('posts', [
    '$http',
    function($http){
    var o = {
        posts: []
    };
    return o;
}]);

o.create = function(post) {
    return $http.post('linktomyliveAPI', post).success(function(data){
        o.posts.push(data);
    });
};

And finally, here's the view:最后,这是视图:

<div ng-controller="ListingCtrl">

<form ng-submit="addProject()">
    <input type="text" ng-model="title"></input>
    <input type="text" ng-model="short_description"></input>
    <button type="submit">Post</button>
</form>

I've been able to successful make GET requests, but for some reason, I can't figure out POST.我已经能够成功发出 GET 请求,但由于某种原因,我无法弄清楚 POST。

My API was built using Django Rest Framework, if that matters.如果重要的话,我的 API 是使用 Django Rest Framework 构建的。

Thanks!谢谢!

I think the way you have added create method is not proper, you have to add that method on factory object我认为您添加create方法的方式不正确,您必须在工厂对象上添加该方法

Put the create method on an object returned from factory.将 create 方法放在从工厂返回的对象上。

In your service为您服务

angular.module('myModule', [])
  .factory('posts', ['$http',function($http){
      var create = function(post) {
          return $http.post('linktomyliveAPI', post).success(function(data){
            o.posts.push(data);
          });
      };

      var o = {
         posts: [],

         // expose create method on factory object
         create: create
      };

      return o;
}]);

Hopefully these will solve your problem.希望这些能解决你的问题。

Fixed it.修复。

I had to change some server-side settings in order to get this to work.我必须更改一些服务器端设置才能使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM