3

I am trying to do a http post into database using AngularJS. My code doesn't shows any error, but my database is not being updated and I can't figure it out why. Here is my code:

//topic-service.js

  (function() {
        'use strict';
        angular.module('topic').factory('topicService', topicServiceFunction);
        topicServiceFunction.$inject = [ '$http', '$q' ];
        function topicServiceFunction($http, $q) {
            var topicService = {
                getTopics : getTopics

            }
            return topicService;

            function getTopics(obj) {
                console.log('-->topicServiceFunction');
                console.log(obj.name);
                var deferred = $q.defer();
                return $http.post('http://localhost:8080/restapp/api/topic',
                        JSON.stringify(obj)).then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        return deferred.reject(response.data);
                    }
                }, function(response) {
                    return deferred.reject(response.data);
                });

            }

        }

    }())

//topic-controller.js

 (function() {
        'use strict';
        angular.module('topic').controller('topicController',
                topicControllerFunction);
        topicControllerFunction.$inject = [ '$scope', 'topicService' ];
        function topicControllerFunction($scope, topicService) {
            $scope.getTopics = getTopics;
            function getTopics(topicId,name,description,categId,userId) {
                 console.log('-->topictrlFunction');
                $scope.topics = [];

                var obj={
        id:$scope.topicId,
        name:$scope.name,
        description:$scope.description,
        id_category:$scope.categId,
        user_id:$scope.userId

        }
        var promise = topicService.getTopics(obj);
                promise.then(function(data) {
                    if (data != undefined && data != null) {
                        $scope.topics = data;
                    } else {
                        $scope.topics = undefined;
                    }
                }, function(error) {
                    console.log('error=' + error);
                    $scope.topics = undefined;
                })
                topicService.getTopics(obj);
                $scope.topics = topicService.getTopics(obj);
            }

        }
    }())

//topic.html

 <!DOCTYPE html>
    <html lang="en" ng-app="myTopics">
    <head>
    <meta charset="UTF-8">
    <script src="../../../bower_components/angular/angular.js"></script>
    <script src="app.js"></script>
    <script src="topics/module/topic-module.js"></script>
    <script src="topics/controller/topic-controller.js"></script>
    <script src="topics/service/topic-service.js"></script>
    <title>Topics</title>
    </head>
    <body>

        <div ng-controller="topicController">
            <div ng-controller="topicController">
                <p>
                    Topic id: <input type="text" ng-model="topicId">
                </p>
                <p>
                    Name: <input type="text" ng-model="name">
                </p>
                <p>
                    Description: <input type="text" ng-model="description">
                </p>
                <p>
                    Id category: <input type="text" ng-model="categId">
                </p>
                <p>
                    User id: <input type="text" ng-model="userId">
                </p>
                <button ng-click="getTopics(topicId,name,description,categId,userId)">Add
                    topic</button>
                <ul ng-repeat="topic in topics">
                    <li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
                        {{topic.id_category}}--{{topic.user_id}}</li>
                </ul>

            </div>
    </body>
    </html>
4
  • 1
    Topic of this post states that you are making PUT request, while in your code you have POST Commented Aug 4, 2016 at 6:50
  • 1
    Does the call get into your API ? Did you check that your API method is called ? If it is the case, it is a problem with the API Commented Aug 4, 2016 at 6:50
  • I checked my post method with Swagger UI and it works. Also, i made a get method in a similar way in AngularJS and it worked. Commented Aug 4, 2016 at 6:57
  • Then it is a problem with your api Commented Aug 4, 2016 at 7:13

1 Answer 1

2

In your service you use $q but return $http promise, that's counter productive, just return deferred promise:

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = JSON.stringify(obj)

      $http.post('http://localhost:8080/restapp/api/topic', data)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }

If it still doesn't work you should try to send urlencoded data and not json :

for this just add this header in your request : headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}

and encode data with $httpParamSerializerJQLike service. (Inject it in your service)

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = $httpParamSerializerJQLike(obj);
      var config = {
         headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
      };

      $http.post('http://localhost:8080/restapp/api/topic', data, config)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.