In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I plan to utilize the .then
method in angularjs. I have created an angularjs controller and services to handle this functionality. Below is the code snippet from the angularjs part:
bolouk.js
:
'use strict';
var app = angular.module('app');
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
Bolouks.create($scope.bolouk).then(function(data){
$scope.saveBolouk = data;
},function(err){
$scope.err = err;
}
);
};
}]);
boloukService.js
:
'use strict';
var app = angular.module('boloukService', ['ngResource']);
app.factory('Bolouks', function($resource) {
return $resource('/api/bolouks.json', {}, {
create: { method: 'POST', isArray: false }
});
});
Additionally, I have included the following code on the rails server side:
bolouks_controller.rb
:
def create
@bolouk = Bolouk.create(bolouk_params)
if @bolouk.valid?
#@bolouk.save
respond_with @bolouk, :location => api_bolouks_path
else
respond_with @bolouk.errors, :location => api_bolouks_path
end
end
private
def bolouk_params
params.require(:bolouk).permit(:boloukcode, :north, :south, :east, :west)
end
Even though the request is sent correctly to the rails server and the data is saved in the database without any issue, I am facing difficulties in retrieving the response of the request. When I run the function, I encounter the following error in the chrome console:
TypeError: undefined is not a function
at Scope.$scope.save (http://localhost:3000/assets/controllers/bolouk.js?body=1:19:39)
at http://localhost:3000/assets/angular.js?body=1:10973:21
at http://localhost:3000/assets/angular.js?body=1:20088:17
at Scope.$eval (http://localhost:3000/assets/angular.js?body=1:12752:28)
at Scope.$apply (http://localhost:3000/assets/angular.js?body=1:12850:23)
at HTMLFormElement.<anonymous> (http://localhost:3000/assets/angular.js?body=1:20087:21)
at HTMLFormElement.jQuery.event.dispatch (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4627:9)
at HTMLFormElement.elemData.handle (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4295:46)
I suspect that there might be an issue with how I am using the .then
method in the angularjs controller. I have also explored the $q
method but still faced the same error. Any suggestions or insights on how to resolve this problem would be greatly appreciated.