Domanda

I am using grails 2.3.4 as the backend for my angularjs 1.2.8 application.

I want to save my data into a database. I tried to implement it like this:

testApp.controller('testController', function($scope, $rootScope, $http, $location) {
$scope.product = {};

$scope.saveProduct = function() {
    console.log('call saveProduct');
    $http
     .post($rootScope.appUrl + '/product.json', $scope.book)
     .success(function(data, status, headers, config) {
  $location.path('/product');
     }).error(function(data, status, headers, config) {
    });
}

});

In principle this should work, because my backend uses @Resource(uri='/product') to provide a RESTFUL API. I can call all existing products like this: http://localhost:8080/testApplication/product.json

However the chrome console diagnosis gives me:

POST http://localhost:8080/testApplication/undefined/product.json 404 (Not Found)

The undefined makes this link not work. Any suggestions how to remove it?

Any suggestions for how I can change my function to make this work?

È stato utile?

Soluzione

It looks like $rootScope.appUrl is undefined when you call $http.post(). Try logging the value of $rootScope.appUrl to the console to make sure. If it's undefined, set it to whatever you need to match the URL that your backend expects.


Edit: I'm not familiar with the specifics of Angular or what exactly gets passed to this method, but you can be a little more robust by checking to see if the variable is defined, like this:

$scope.saveProduct = function() {
  var url = 'products.json';

  if($rootScope && $rootScope.appUrl) {
    url = $rootScope.appUrl + '/' + url;
  }

  console.log('call saveProduct');
  $http
  .post(url, $scope.book)
  .success(function(data, status, headers, config) {
    $location.path('/product');
  })
  .error(function(data, status, headers, config) {});
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top