简体   繁体   中英

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.

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.

My API was built using Django Rest Framework, if that matters.

Thanks!

I think the way you have added create method is not proper, you have to add that method on factory object

Put the create method on an object returned from factory.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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