So I am learning Angular , and I would like to make a web Application which consumes a Restful Web service . So my page looks like this :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html ng-app="Tripeew">
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tripeew</title>
</head>
<body ng-controller="region">
<h1>Hello World !!</h1>
<p>Id : {{All.id}}</p>
<p>Nom :{{All.nom}}</p>
<br/>
<script type="text/javascript">
var myapp = angular.module('Tripeew',[]);
myapp.controller('region',function($scope,$http){
$http.get('http://localhost:9090/Tripeew_V1.0/webresources/tripeewws.regions/3').succes(function(){
$scope.All = response.data ;
});
});
</script>
</body>
</html>
But I can't have the result of the ws , which is working via URL , all I get is this :
Hello World !!
Id : {{All.id}}
Nom :{{All.nom}}
Use this syntax:
$http.get('http://localhost:9090/Tripeew_V1.0/webresources/tripeewws.regions/3').then(function(response) {
$scope.All = response.data ;
});
Error is occured because AngularJS version that author uses is 1.6.9, but success()/error() was deleted in 1.6.0-rc.0 version (see Changelog).
BREAKING CHANGE:
$http's deprecated custom callback methods - success() and
error() - have been removed. You can use the standard
then()/catch() promise methods instead, but note that the method
signatures and return values are different.
success(fn) can be replaced with then(fn), and error(fn) can be
replaced with either then(null, fn) or catch(fn).
Before:
$http(...).
success(function onSuccess(data, status, headers, config) {
// Handle success
...
}).
error(function onError(data, status, headers, config) {
// Handle error
...
});
After:
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}, function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
// or
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
Note: There is a subtle difference between the variations showed above. When using $http(...).success(onSuccess).error(onError) or
$http(...).then(onSuccess, onError), the onError() callback will
only handle errors/rejections produced by the $http() call. If the
onSuccess() callback produces an error/rejection, it won't be
handled by onError() and might go unnoticed. In contrast, when using
$http(...).then(onSuccess).catch(onError), onError() will handle
errors/rejections produced by both $http() and onSuccess().
The success syntax is deprecated since Angular 1.4.3. If you're using a newer version of Angular you should use the then syntax.
Well, there are two problems with your code. First one is obvious as everbody have told you to correct the typo of sucess to success and second you're not passing response to your handler function that you wrote in success. I mean you should pass the data like .success((response)=> $scope.All = response.data).
Notice, I am passing response to success callback.
Moreover, you better use the following syntax to make http requests with angularjs
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Related
I have an angular controller which makes an HTTP GET request and on the promise return, calls either a success of error function. My code right now will sometimes execute the success function after the GET request returns and sometime execute before it. Is there something I'm messing up in my promise handling? Something to note, sometimes the http GET doesn't even get called (or at least its breakpoint) and the success function happens regardless. Here is my code:
.controller('CheckOutCtrl', ['$scope', '$http', function($scope, $http) {
//Controller for checkout feature
$scope.owner = "Unclaimed"; //Default owner
$scope.endDate = "";
$scope.unclaimed = true;
$scope.showpopup = false; //Should we show the popup that checkout is successful or returned
$scope.currentOwner = false; //Show return date
$scope.popuptext = "";
$scope.checkOut = function(){ //Extends or creates a check out
$http.get("/checkout/extend/code/" + code + "/username/" + userName).then(
function success(response, status, headers, config) {
console.log("Checked out or extended");
$scope.showpopup = true;
$scope.currentOwner = true;
$scope.popuptext = response.data; //Show airport checked out until or error
console.log($scope.popuptext);
init(); //Update current owner
},
function error(response, status, headers, config) {
$scope.error = response;
console.error("Check out error:", response);
}
);
};
}
I discovered this was happening because Angular caches GET requests for some time and the cached version of my request was being used.
I have searched it a lot , in all cases , they usually want to show it on HTML directly , but my purpose is to use the data in Angular JS only.
angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
var url ;
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
//alert(JSON.stringify(url.data));
});
//var REST_SERVICE_URI = 'http://localhost:8080/HomeAccessService-1/user/';
var REST_SERVICE_URI = JSON.stringify(url.data);
var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};
return factory;
function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
I want to use this url data in other methods , the data is actually a REST API URL which i put in data.json file
{"data":"http://someotherip:8080/Service/user/"}
It shows object Object when alert ,
I dont want to show it in HTML but to use the data in angular js methods.
Alert is showing up before your response reach. Put alert inside request promise. You will get the response.
and use json.stringify(response.data) to make a json string
You should call the alert inside the promise otherwise it will be undefined when you alert it,
$http.get('/Service-1/static/js/data.json').then(function(response) {
url = response.data;
alert(JSON.stringify(url.data));
});*/
Inorder to display the correct data, you should use JSON.stringify()
alert(JSON.stringify(url.data));
You can do one of the two things
1. Add REST_SERVICE_URI = .. instead of that alert statement OR
2. Add those geturl call inside fetchAllUsers function and then do your next steps once you get resopnse.data
//// Add url part inside get response
var url;
var REST_SERVICE_URI;
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
REST_SERVICE_URI = JSON.stringify(url.data);
});
...
//// OR do it in sync
function fetchAllUsers() {
var deferred = $q.defer();
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
REST_SERVICE_URI = JSON.stringify(url.data);
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
});
return deferred.promise;
}
$scope.jsondata=json.stringify(response.data)
console.log(jsondata.url);
take all the json in one javascript variable then travarse that using loop or variable like jsondata.url and use it in ur future api call.
I'm trying to call a webservice that requires me to pass a JSON object to it. Though I'm not sure whether I'm doing it right. My service does the following:
this.updateAddressDetails = function (address, personId) {
var url = 'http://213.456.123.456:8080/Address?' +
'action=updateAddress' +
'&personId=' + personId +
'&address=' + JSON.stringify(address);
return $http.get(url);
}
But I get the following error server side (I'm using Java Servlets):
Error parsing HTTP request header
Which leads me to assume that I'm not passing the JSON to the server the correct way. Any tips?
Try something like this if your are working with angular JS:
$scope.myFunc = function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
I have the following Javascript code in the controller of my web page.
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
});
$http({
method: 'GET',
url: $scope.properties.Properties.dataLocation
}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
The structure of the json file to be fetched is not the problem.
It is supposed to first run the $.getJSON command and afterwards run the $http-request, since the $http request gets its url from the variable that is defined in the $.getJSON part at the top but instead when i do a console.log(properties) just below it, it spits out "undefined".
Why is the code not executing in the order that it is written?
The code is executing in order that it's written, just callback functions are being executed when the corresponding requests are complete. So you should put the second call in the first callback:
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
$http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
});
It is executed asynchronous so both call will be done independantly.
$.getJSON has third parameter - success callback this is the way to sync those.
http://api.jquery.com/jquery.getjson/
Not sure why you are mixing jQuery AJAX and Angular $http ?
You could use the JQuery.done, which will execute your code after your request has finished.
Example:
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
The same way that you have already got the line $scope.properties = data; to run after the JSON has been received. You put it in the callback function you pass to getJSON.
Why is the code not executing in the order that it is written?
It is.
getJSON(url, foo) means "Make an HTTP request to the url and set up an event handler to call foo when the response is received".
You seem to be expecting it to wait for the response before doing anything else. That would lock up the UI and be horrible.
My javascript function is working in angular, but I want to have an error function to determine of there is an error when a bad request is sent. How could I put the error function in this kind of format of code in javascript? Thanks in advance to those who want to help me.
$scope.submitLogin = function()
{
var request = {};
request.url = '/account/users/login';
request.method = 'POST';
request.data = angular.toJson($scope.students);
var onSuccess = function(data, status, headers, config, statusText)
{
alert('success!');
$location.url('/examdirection/');
};
httpRequest(request, $scope.response, onSuccess);
};