Angular JS Get HTTP Request Parameter - angularjs

I'm migrating a JSP/Spring project to Angular JS 1.X. Currently I'm stuck in following situation, appreciate if anyone can help.
My application is redirecting to a 3rd party app and after submitting a form response is coming back to again my application. In spring I used to get the request parameter using following code. How can I get the request parameters in Angular JS?
#Autowired
private HttpServletRequest request;
..
Enumeration paramsEnum = request.getParameterNames();
while (paramsEnum.hasMoreElements()) {
String paramName = (String) paramsEnum.nextElement()
....
}

Not sure I understood the question because with Java/Spring we access the params sent by angularJS.
Anyway, If you want to access a Url parameters of the current view you can use the angularjs $location service:
$location.search()
For example taking the 'impersonate_token' from the url and adding it to some variable:
if($location.search().token){
var token = $location.search().token;
url += "?impersonate_token=" +token;
}
if you want to manage the Url parameters send to the server side, you can do with angularjs $http service like this:
$http({
url: your/url,
method: "GET",
params: {
param_1: $scope.some_data
param_2: $scope.some_data2
}
});

$http.get(url)
.then(function(response) {
$scope.myWelcome = response.data;
});

Related

Java, Struts 1.2, Json Angular JS - How can I get json response from action class to my Angular JS page?

I need a clarification on this below technology
Current technology:
Struts 1.2
Jsp
Java
AngularJS
Currently I am trying to migrate one of my jsp page to AngularJS page which is client req.
I am trying using below code to get json response, but I unable to get the json data in my jsp page.
Question:
1) How to get a json object from the response of action class in struts?
2) Currently :
Note: one of temporary way I able to get json object in jsp using session.setAttribute() and getAttribute.. but its not rite way to do it as I just getting all my table data and put in session. apart from this any way please help..
Code :
In jsp:
$scope.getDataFromServer = function() {
$http({
method : 'GET',
url : '/com/test/Browse.do'
}).then (function successCallback(response) {
var itemsDetails = JSON.parse(response);
$scope.person = response;
}).error(function(data, status, headers, config) {
});
};
**//The above response getting as object unable to get json object.**
In action class:
public void doExecute(ActionContext ctx) throws IOException,
ServletException {
PersonData personData = new PersonData();//[PersonData class available]
personData.setFirstName("Mohaideen");
personData.setLastName("Jamil");
String json = new Gson().toJson(personData);
ctx.forwardToInput();
}
I able to get the data using session attribute like below, but it is not rite way will make me to avoid struts action and also whole table data putting in session I not sure whether it will rite way or secure way.
var data1 = '<%=session.getAttribute("jsonobjtest")%>';
Can please help me out to get the rite way to implement with struts 1.2 and angularjs? if we cannot do it help me guide me the workaround how to achieve with angularjs?
Hie there from my understanding you want to get a json object from your Java backend
here is how i do http requests in AngularJs 1.5.11
(function () {
'use strict';
angular.module("myapp")
.controller("HelloController", function($scope,$http){
$scope.getDataFromServer = function() {
$http.get("/com/test/Browse.do").success(function(response,status){
//console.log(response,status); check your data
$scope.person = JSON.parse(response);
});
}
});

return json response from spring mvc to a html/angular view

I have a html/angular view which needs to get data from spring mvc controller which returns Json response.
Previously I used angular, getting json calling a REST url.
Not sure how to do the same when spring mvc controller returns a json response.
Thanks.
My sample code.
js
function sendMessage(message) {
$.ajax({
url : "/sample/push/" + message,
processData : false,
contentType : "text/html; charset=utf-8",
type : 'POST',
success : function(response) {
// get response
},
error : function(request, status, error) {
},
});
}`
controller
#RequestMapping(value = "/push/{message}")
public #ResponseBody String processResult(#PathVariable String message) {
// "your json String"
return pushService.pushMessage(message);
}
ajax call and spring MVC tutorial - link : this tutorial XD
Keep in mind some concepts as partial view, angular controller, angular service and how to make async call using the $http angular service.
Basically you create a Controller (js), a Service (js) and a partial View (html)
In the service you implement all data logic and rest api calls
In the controller you manipulate data retrieved using the service and prepare it to be presented in the partials
In the partial you "bind" (and it is shown to the user all data, actions, etc) the info in the controller

how to use response.redirect in webapi+asp.net?

I want to redirect to another .aspx page from WebAPI. I have used this code but it is not working:
string url = "http://localhost:61884/UserList.aspx";
System.Uri uri = new System.Uri(url);
return Redirect(uri).ToString();
You don't. (or your description of the problem is not accurate)
Web API is meant to retrieve data or persist data, it is a way to interact with the server from the client without having to do the traditional form post or page request calls. The caller (javascript based on your question tag angularJs) needs to execute the redirect once the results from the call to the Web API are retrieved.
This is good SOC (separation of concerns), the business logic in the Web API should not care about routes (angularjs) / web pages.
Even if you wanted to the Web API, because of how its called, can't redirect the client.
Summary: The Web API code itself should not any type of redirecting of the client. The client should handle this.
Sample call to web api and redirect from angular code:
$http({
url: "/api/SomeWebApiUrl",
data: {},
method: "POST",
headers: { 'Content-Type': "application/json" },
responseType: "json"
}).then(function (response) {
if(response.data.somethingToCheck === someConditionThatWarrentsRedirect)
$window.location.href = "~/someOtherUrl/";
});
try something like this:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Hope that helps.
Redirect from asp.net web api post action
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}

AngularJS $resource GET params appear in URL

My REST backend [ based on NodeJS/express/mongojs] is complaining 404 (not found) when Params are attached as part of URL. Backend rest interface is coded as below;
var express = require('express');
var router = express.Router();
router.get('/login', auth.signin); //auth.signin is code to verify user
Above REST service is consumed by AngularJS based frontend through $resource as below;
Definition:
angular.module('myapp').factory('signinmgr', function($resource) {
return $resource("http://localhost:3000/login", {}, {
'get': {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}});
Usage:
signinmgr.get({'username':'myname', 'password':'mypass'}, function(data){
//success
}, function(x){
//failed
});
Problem:
Frontend code above produces a URL to consume REST service where parameters are part of URL i.e. http://localhost:port/login?username=myname&password=mypass [if I use GET method, POST is OK]. I wanted my front end to keep URL as http://localhost:port/login and post any parameters through body as backend is using req.body.paramName to read those. [Actual Solution]
If (1) cannot be done, and my frontend is sending params as part of URL, I needed help as to know how to equip my backend to allow this URL with parameters so that backend doesnt return 404 as the base URL http://localhost:port/login is already there.
PS: for (1), I tried this thread with data:{username:'',password:''} but of no use. Please help if I am missing something very obvious or some concept.
Try the $http service instead:
angular.module('myapp').factor('signinmgr', function($http) {
return {
login: function (username, password) {
$http.post("http://localhost:3000/login", {
username: username,
password: password
}
}
};
});
signinmgr.login('myname', 'mypass').then(function(data){
//success
}, function(x){
//failed
});
Each request that my nodejs/expressjs backend receives has three places for passed attributes;
params{}
query{}
body{}
My problem (1) cannot be fixed in case I want to use GET method since with GET request parameters are visible as part of URL i.e. http://localhost:port/login?username=myname&password=mypass. To send my username/password I had to use POST that sends parameters as part of body{}.
My problem (2) was that I was using GET and mistakenly looking for parameters in body{} of request. Instead, parameters passed as part of URL in GET request are added to query{} of the request.

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Resources