Angularjs get Json from $routeParams - javascript

I have a controller which will save address data and will change the location (using $location.path("/checkout/"+ $scope.checkOutAddress);)to the next page with the json response as parameter by
$routeProvider.when('/checkout/:checkOutAddress', {
templateUrl : 'partials/checkOut.html',
controller : 'myController'
});
In the checkout controller trying to get the value using the below code
mCommerceApp.controller('myController', function($scope,$sessionStorage,$location,$routeParams,MCommerceService) {
$scope.checkOutAddress=$routeParams.checkOutAddress;
console.log($scope.checkOutAddress);
});
So now the problem is I am not able to get the json value. It is coming as an object. The browser log displays [object Object]. Any help how to get the $routeparama as json?
Thanks.

try to stringify it
var json = JSON.stringify($scope.checkOutAddress);
but i'm not sure it's the good way to pass data from controller to another, you can use a provider to stock datas.
App.provider('Data', function() {
//Properties declaration
this.tosend = '';
//Setters
this.setTosend = function(tosend) {
this.tosend = tosend;
};
//Getters
this.getTosend = function() {
return this.tosend;
};
});

Related

string is empty after is post with jquery post in MVC controller

I want to post a string to the MVC controller and return a partial view. The view returns but the string shows empty.
My controller:
public PartialViewResult CreateServiceRateModal(string serviceId)
{
System.Diagnostics.Debug.WriteLine(serviceId);
//var a = JsonSerializer.Serialize();
ViewData["ServiceId"] = serviceId;
return PartialView("~/Views/ServicesManager/_CreateServiceRate.cshtml");
}
Jquery:
function CreateServiceRateModal() {
var Id = $('#ServiceId').val();
$.post('CreateServiceRateModal', JSON.stringify(Id)).done(function (data) {
$('#modal-placeholder').html(data);
$('#modal-placeholder').find('.modal').modal('show');
});
I have checked the Id before posting is not empty.
You need to pass it with a property name matching your controller method parameter name as an object, so change it to this, you can read more on the documentation (https://api.jquery.com/jquery.post/):
$.post('CreateServiceRateModal', { serviceId: Id }).done(function (data) {
$('#modal-placeholder').html(data);
$('#modal-placeholder').find('.modal').modal('show');
});

POST to a REST service using Ajax is failing

I am working with a javascript client that I am trying to use to communicate with a server. I have a Javascript function that is POSTing to a Spring Boot REST service. The service is a simple test service that doesn't do much...
#RequestMapping(method = RequestMethod.POST,value="/testservice")
#ResponseBody
public String testPostRequest(#RequestParam String someText)
{
System.out.println("Reached the counting service! Param value: " + someText);
if(someText != null)
{
...
perform some actions
...
}
return("Success");
}
The Javascript I am using to send POST requests to the server is below:
var sendWords = function(toSend) {
var data = { DataList : [toSend] };
var param = { someText: data };
$.post("http://localhost:8080/testservice",param,
function(status,ret) {
alert("We're back "+status);
});
};
The toSend parameter is just a string containing some text that will be posted to the service. Note that the port for the service was set to 8080 in the server's application.properties file.
When I call the Javascript function and post the string to the service, I get the following log message from the server:
2019-07-28 20:00:06.292 WARN 80844 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'someText' is not present]
I am doing something wrong, but cannot figure out what it is. I am sending an object that is tagged as the someText string, but it is not being recognized by the server for some reason.
Can someone tell me what I am missing? How do I get this to work?
var data = { DataList : [toSend] };
var param = { someText: data };
Here data is not string.
You may need to stringify it.
var param = { someText: JSON.stringify(data) };
You are missing the value in the #RequestParam(), such as #RequestParam(value="someText", required=true).
You could use #PathVariable too.
This could be helpful:
#RequestParam vs #PathVariable

How to get an object from service and use if after getting it

I am trying to get an object from a service and after that use the data found.
Here is my service, i am simply reading a local json file
myApp.service('myService', function($http) {
this.readFile = function(file) {
return $http.get(file).then(function(result)
{
return result.data;
});
};
});
I have this in my controller
function callService(fileName){
var data = myService.readFile(fileName).then(function(result)
{
console.log(result);
return result;
});
return data;
}
In other function that I am calling using ng-init I have this
storage = callService(fileName);
var test = storage.images;
The problem is that I am getting an error saying angular.js:14794
TypeError: Cannot read property 'images' of null
After that the console print the object with the image properties
It seems that the service is being executed at the last

AngularJS $resource - Call the method via a variable?

I have an Angular $resource as
var Client = $resource('/api/clients/:id',{id : '#id'}, {
query: { method: 'GET' })
I want to be able to call, say query() or save() via a variable. I.e. I want to say
var method = 'query';
Client[method]()
But this returns an error: Unexpected token [
Why?
It's not an object, which is why you get the error. You can call the method like so:
Client.query();
If you really want to call it via a variable you could map it to an object and call it that way, I wouldn't recommend it though:
var resources = {
query: Client.query,
somethingElse: Client.somethingElse
};
var type = 'query';
resources[type]();

calling controller from method from JavaScript

I am developing a web site using MVC 3 razor, in which I have the following situation:
A controller method:
public ActionResult MyControllerMethod(int parameter){
''go to bd a do some staff
IList<My_Custom> datafromDB = MyService.GetData(parameter);
'returns to my string tuped view
return View(datafromDB );
}
A strong typed view in which I use JavaScript:
#model IList<My_Custom>
<script type="text/javascript">
function getData()
{
var parameter = document.getElementById('myParamater').value;
$.get('/MyController/MyControllerMethod/' + parameter, function (data) {
loadData();
}
);
}
function loadData()
{
clearData();
datos = #Html.Raw(Json.Encode(Model));
//do some stuff with datos
}
</script>
The JavaScript call to the controller works fine but my problem is that the string typed view seems like is not taking the new value for the #model, so keeps loading the same information.
Although I have debugged the action controller and it returns different data every time.
So is there any way to refresh the Model value of a string typed view?
I also tried to process the data value of that line
$.get('/MyController/MyControllerMethod/' + parameter, function (data) {
but I wasn't successful doing that.
Your action return view, that's why nothing works. How your code works:
Load data in action, then generate view with json on the page
Send requst to the server and receive html with json (all this data are in memory),
then you access json from first step
How it must work:
Create view
Send request to the server (another method, that returning Json)
Access data
public ActionResult YourJsonAction(int parameter)
{
IList datafromDB = MyService.GetData(parameter);
return Json(datafromDB, JsonRequestBehavior.AllowGet);
}
function getData()
{
var parameter = $('#myParamater').val();
$.get('/MyController/YourJsonAction/' + parameter, function (data) {
//data from YourJsonAction
});
}

Categories