2014-02-13 61 views
-1

我使用grails 2.3.4作爲我的angularjs 1.2.8應用程序的後端。通過json保存數據

我想將我的數據保存到數據庫中。我試圖這樣實現它:

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) { 
    }); 
} 

});

原則上這應該工作,因爲我的後端使用@Resource(uri='/product')來提供一個RESTFUL API。我可以打電話給所有現有的同類產品:http://localhost:8080/testApplication/product.json

然而鉻控制檯診斷給了我:

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

undefined使得這個鏈接無法正常工作。任何建議如何刪除它?

對於如何改變我的功能來完成這項工作的任何建議?

回答

1

當您撥打$http.post()時,看起來像$rootScope.appUrlundefined。嘗試將$rootScope.appUrl的值記錄到控制檯以確保。如果是undefined,請將其設置爲任何您需要匹配後端所需的URL。


編輯:我不熟悉的角的細節或精確獲取傳遞給此方法是什麼,但你可以是一個小更強大的通過檢查,看是否該變量的定義,像這樣:

$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) {}); 
} 
+0

Thx爲您的答案!問題在於,唯一一個把我從保存中分離出來的詞是'undefined'。這個URL會保存我的數據:'http:// localhost:8080/testApplication/product.json'任何建議如何殺死未定義的JavaScript? – mrquad

+1

我編輯了我的答案,告訴你如何。 –

+0

Thx爲您的答案!我的問題是,我仍然得到這樣一個鏈接:'http:// localhost:8080/product' – mrquad