angularjs Rest API - angularjs

I've read up many articles on angularjs and REST but could not found any solution. Through java script I am calling api method, which is routed method as:
[Route("api/Comments/{docId}/comment/{revId}/get/{size}/getNumber/{number}")]
[HttpPost]
public IEnumerable<Student> Get(int docId,int revId,int size, int number)
{
// loadienter code hereng list here
return list.ToList();
}
//java script code
var url='api/students/' + docId + '/student/' + revId + '/get/'+size+'/getNumber/'+number';
$http.get(url).success(function (response) {
if (callback) callback(response.result);
};
But the method in controller class is not executing..How to solve this issue? P
Please give me some suggestions..

If in your angular controller you have just that code for the call to the api it looks like when you are constructing your url variable you haven't included on the front of it what the domain is that you are hitting. such as http://localhost/ if your debugging it locally.
Also your route is defined to start as api/comments/ on your WebApi however in your javascript url you have api/students/

Related

(Angular) Js embedding an MS Word doc using AJAX return data as the URL

[Update] there is a 50 point bonus, which I will up to 200 for a working fiddle
[Update] while I prefer an AngualrJs solution, I will also accept plain JS - just anything to get me over this impasse ... a GET call to my server returns a URL and I want to embed that document into my HTML
With reference to my previous question, #MaximShoustin 's answer seemed perfect, but I am having problems.
The URL in that solution there is hard coded, but I want to get mine by AJAX. When I do, the document is not embedded, but I see no error in the developer console.
I made this fiddle, where I added these lines
to the HTML
<iframe ng-src="{{cvUrlTrusted_2}}"></iframe>
and, to the controller
app.controller('Ctrl', function($scope, $sanitize, $sce, $http) {
added , $http
and
// new stuff follows
var url = 'http://fiddleapi.rf.gd/getDocuemntUrl.php';
/* The URL contains this code ...
<?php
echo('https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc');
?>
*/
$http.get(url)
.success(function(data, status, headers, config)
{
var cvTrustedUrl_2 = 'http://docs.google.com/gview?url=' + data.trim() + '&embedded=true';
$scope.cvTrustedUrl = $sce.trustAsResourceUrl(cvTrustedUrl_2);
})
.error(function(data, status, headers, config)
{
alert('Urk!');
});
If you invoke the API at http://fiddleapi.rf.gd/getDocuemntUrl.php you will see that it returns the same document URL as was hard coded in the solution.
Please, first check my code, lest I have made a mistake.
Long description, short question : how can I embed a document who's URL is returned from an AJAX API into an HTML document using AngularJS? Free free to fork the fiddle.
Your fiddle doesn't work because of cross domain problem: http://fiddleapi.rf.gd/getDocuemntUrl.php
So I loaded simple JSON file with content:
{
"val":"https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc"
}
and:
$http.get('data.json').then(function (resp){
var cvTrustedUrl_2 = 'http://docs.google.com/gview?url=' + resp.data.val + '&embedded=true';
$scope.cvUrlTrusted_2 = $sce.trustAsResourceUrl(cvTrustedUrl_2);
});
Demo Plunker
It works fine so the problem is in your http://fiddleapi.rf.gd/getDocuemntUrl.php because this URL doesn't work in Postman too. I get:
This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
be sure you configured it well

Passing a list from AngularJS to Spring Controller

I am calling a Spring API from AngularJS, where I am trying to pass a list of model object as the param.
data.append('updatedItems', $scope.QuoteList);
$http.post('updateQuotes', data).success(function(response) {
console.log(response);
});
Then in Spring controller, I am trying to receive as below,
#RequestMapping(value = "/updateQuotes", method = RequestMethod.POST)
public ArrayList<ConsumerPrice> updateQuotes(#RequestBody List<ConsumerPrice> updatedItems, ConsumerPrice consumerPrice) {
System.out.println(updatedItems);
return null;
}
At this point, I get an exception as mentioned below. I am not sure if this is the correct approach to pass a list from Angular to Spring controller.
Invalid mime type "application/json;charset=utf-8, multipart/form-data;
I found few guidance in the internet and tried like, providing the consumes header but nothing helped. Any guidance will be great
I tried providing #PathVariable at the spring controller but didnt help
Finally I was able to resolve this. There is nothing in the spring controller but i changed the way we pass the Javascript array from Angular controller.
The first 2 lines down below is the difference on how I add the list to formdata array. That helped me to fetch the values in Spring Controller.
$scope.formData = [];
$scope.formData = $scope.cQuoteList;
$http.post('updateQuotes', $scope.formData).success(function(response) {
$scope.userQuotes();
});

Session Handling in Angular JS, with Spring MVC

I am creating a project in AngularJs at frontend and Spring MVC in backend.
Now assume when a used logged in and if he wants to update his information, for this i have created an api which request for emailid and update the rest object in database of that email id
Now i have some questions,
1.) I dont want to use CookieStore or others sessionStorage or localstorage (because of my personal vulnerability experience and also i want to use session only) in Angular, how can i do it in angular with Spring MVC.
2.) How can i retrieve the email id from session to update data?
3.)If a user goes to another page how can i maintain that session in another page, how can i check that session is there and user is authentic to see the page
Read a lot about it but unable to find the exact solution with session. Answer over there is manage it by cookieStore.or localstorage, Please help
Let's try and see what is happening here using cookies is the right way to this, you may think it is not safe but is the safest way to do it. With cookies you will be sharing the same session in all tabs, so you can handle in all tabs and share it.
There is also an alternative option and is using URL rewriting, quoting #vanje in this question in stackoverflow
the session is only identified via a URL parameter containing the session ID. So every internal URL of your web application has to be enhanced with this parameter using the method HttpServletResponse.encodeURL(). If you are using a web framework like Wicket, chances are good that this is already done for you.
Lets go now with the Angular JS - Spring MVC approach:
There is no need to access the session within the Angular JS front-end, if you need to use it and you are using JSP you may use scriplet to retrieve the information openening a <%= session.getAttribute("user") %> , but as I said there is no need to do this. You may call your function, and retrieve this information in your controller in Spring.
You have a controller in angular JS that calls with http to your REST controller in Spring such like this. assuming that you save your user first in session:
$scope.getUserInfo= function () {
$http.get(appContextPath +'/rest/getuser/').success(function (data) {
$scope.user= data;
});
};
You may have a request mapping for the URL above:
#RequestMapping(value = "/rest/getuser", method = RequestMethod.GET)
#ResponseBody
public User getUserInfo (HttpSession session) {
User nUser = session.getAttribute("user");
return nUser;
}
I think the best way is to create a method in your AngularJS controller and then call it.
Java code:
#RequestMapping(value = "/menu/get", method = RequestMethod.GET, headers="Accept=*/*")
public #ResponseBody Empleado showMenu(HttpSession session) {
Empleado empleado = (Empleado) session.getAttribute("empleado");
return empleado;
}
AngularJS code:
angular.module('myModule')
.controller('myMenuController', ['$scope', '$http'
function($scope, $http){
getEmpleadoInfo = function () {
$http.get(myContextPage + '/menu/get')
.then(function(data) {
$scope.empleado = data;
})
}
getEmpleadoInfo();
}]);
This way, when you load the page, the object will be loaded on the scope.

Passing and retrieving complex objects from Angularjs to Web Api

I have a form in angular where a user enters various criteria which I then want to pass to Web Api and get a result after queries are run. I originally thought of this as a "Get" but had trouble passing complex objects to the Web Api. With some advice, I then used a Post and was able to pass the criteria run the query in the Web Api but I had trouble getting the result back in Angular. The Web Api method is run and gets the results. But I don't see the results in the data service.
What is the best approach where the criteria for a query is multiple fields and some are lists? I haven't been able to find any good examples.
Here is the Web Api method:
[HttpPost]
public IEnumerable Post([FromBody] FrequentPawnerReportCriteria criteria)
{
var repo = new FrequentPawnerReport();
var result = repo.GetReport(criteria);
return result;
}`
Here is the dataservice:
function getFrequentPawner(criteria) {
return $http.post("/api/FrequentPawner/Post", criteria)
.then (getFrequentPawnerComplete)
.catch(getFrequentPawnerFailed);
function getFrequentPawnerComplete(response) {
var x = response
return response.data.results;
}
function getFrequentPawnerFailed(error) {
alert("XHR failed for frequent pawner report: " + error.responseText);
}
}
And here is the controller code:
function getTopPawnerResults(criteria) {
return DataContext.getFrequentPawner(criteria)
.then(
function (result) {
vm.frequentPawnerReport = result.data;
return vm.frequentPawnerReport;
});
}
Simply use JSON. Use JSON.stringify() to parse JSON object to string and POST it. Similarly, return JSON string from server, and assign it to variable in Angular. It will be automatically converted to JSON object.
I think when you make your post request, you need to have a callback function that would get invoked when your Web Api returns. Within that callback function you can update your $scope variables which will make your web ui show the response from the server. You can find an example of what I mean here: https://docs.angularjs.org/api/ng/service/$http
The gist of it:
$http({
method: 'POST',
url: '/path/to/your/web/api',
function(success) {
console.log('Successfully executed the api call');
$scope.response = response; // change this to match the data you are expecting from the server response
},
function(failure) {
console.error('There was an error');
$scope.failure = failure; // change this to match your failure response
}
);
Thanks for responding. The project is a mix of web forms and angularjs. I am migrating the app and didn't notice this form had a conflict which was causing a post back and making it look like the result was not being returned. I took the form into a separate project and was able to get the results I was going for.

angularjs resource Authentication Header based on request body

I'm trying to use Resource with APIs protected by HMAC authentication methods. So I need to append "Authentication" header to the request.
In this example code I get the Article from the API with GET and update it with "update" custom method. For the update I need Authentication header. The problem is that $scope.article is undefined when I define the header.
getAuth function calculates the sign.
Suggestions?
function EditCtrl($scope,$resource,articleId) {
var Article = $resource('/blog/articles/:articleId',
{articleId:articleId}, {
update: {
method:'PUT',
headers: {Authentication: getAuth('key','PUT','/blog/articles/'+articleId,$scope.article)}
}
});
var article = Article.get();
$scope.article = article;
$scope.save = function(){
article.$update();
}
}
function getAuth(key,verb,resource,data) {
//data is undefined there
content_md5 = CryptoJS.MD5(JSON.stringify(data));
message = verb+'\n'+resource+'\n'+content_md5;
hash = CryptoJS.HmacSHA512(message, key);
var sign = "AuthHMAC 0123456789:"+hash.toString(CryptoJS.enc.Base64);
return sign;
}
I improve Alan's solution using three elements:
factory service that shares the key
controller that sends the httpRequest
httpRequestInterceptor that sets the header
The controller calls a setKey() provided by a factory service that calculates the header. Finally the httpResponseInterceptor sets the header of request calling getKey() provided by a factory service.
Solved!
I'm working on something similar right now.
I believe the answer lies in using $httpProvider.defaults.transformRequest functions, I don't have it complete yet, but the basics as described in the docs: http://docs.angularjs.org/api/ng.$http
I think are this:
var authModule = angular.module('my.AuthModule', [], myAuthModuleCfg);
function myAuthModuleCfg($httpProvider) {
$httpProvider.defaults.transformRequest.push(myRequestSigner)
}
function myRequestSigner(data, headersGetter) {
// do some signing, etc...
}
(Apologies for only posting a link instead of an entire solution) have a look at 'Monofraps's angular-node-hmac-example on GitHub (MIT license).
For Hmac/SHA512 encryption, it uses the (deprecated) CryptoJS library, which I'd probably swap for the Forge cryptographic library (CryptoJS has now been abandoned).
I have not tried it, but if you look at lower level API $http, it has a methods that take in config as a parameter. This config i think contains the headers property that you can update before making the request. Here is the signature for PUT
$http.put(url, data, config)

Resources