How to get data from a web service with Angular.js - angularjs

Im trying to get data using Angular
and I am trying to call a CurrencyConverter method as shown at this address: http://www.webservicex.net/WS/WSDetails.aspx?WSID=10
My code does not work:
please help me.....
Thank You
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http){
$http({
method : "GET",
url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=USD"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;});});
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
Output
Notfound

The api endpoint appears to be giving a cross origin error, the response.statusText also ends up being empty so you can't tell that the http call errored out in your app. If you change the error message to some string you'll see http call comes back.

Related

Getting error when trying get JSON from remote url

I'm trying load this json file from remote url. In the beginning I was using $http.get function, but I was getting the next error message:
CORS 'Access-Control-Allow-Origin'
Now I am using JSONP, but nothing happens.
service.js file:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http){
return $http({
method: 'JSONP',
url: 'http://vagalumewifi.com.br/timeline.json'
}).success(function(response){
return response.data;
}).error(function(err){
return err;
});
}]);
controller.js file:
angular.module("elcomaApp", []).controller('MainController', ['$scope', 'ElcomaService', function($scope, ElcomaService){
$scope.name = 'Natanael Santos';
console.log($scope.name);
ElcomaService.success(function(data){
$scope.elcomaData = JSON.parse(data);
var i = 0;
for (x in $scope.elcomaData){
console.log(i);
i++;
console.log(x.date);
}
}).error(function(data){
console.log(data);
});
}]);
app.js file:
var app = angular.module("elcomaApp", ['ngMaterial', 'ngRoute']);
I already hava read a lot of articles on stackoverflow, but no one work for me.
I'd suggest using $http.jsonp(url) method:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http) {
$http.jsonp('http://vagalumewifi.com.br/timeline.json')
.success(function(data) {
console.log(data); // you can't `return` here...
}).error(function(err){
console.err(err);
});
}]);
Note: be warned that you can't expect that return in an async method has the same behavior as in a sync environment... :-)
Your original error is your clue. The endpoint server won't allow access from another domain.
CORS: Cross Origin Requests
You need to allow access on the endpoint server for the type of HTTP method you want to use (i.e. GET, POST, HEAD, ...) Additionally depending on what you're doing you may need to allow for an OPTIONS request, see Preflighted Requests in the MDN documentation above.
If you don't have access to that server you may need to do a work around by making $http call a script on your server that will fetch the file for you. I've done this before using PHP as a proxy and using PHP's file_get_contents function to grab files from other servers of a different domain.

How to make a download button with the AngularJS $http service

Is it possible to trigger a download via a button and using AngularJS $http service in the background to provide the file?
I want to have a simple button, which starts a file download without opening a new window. Furthermore I have to set the Authorization inside of the header.
So far I did this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.startDownload = function() {
var auth = ""; //username + password
$http.defaults.headers.common['Authorization'] = auth;
//this will return a file
$http({
method: 'GET',
url: 'https://upload.wikimedia.org/wikipedia/commons/1/1c/FuBK_testcard_vectorized.svg?download'/*,
headers: {
'Authorization': 'Basic efhjwefjfbweikabfkwhfb'
}*/
}).then(function(){
//????
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button type="button" ng-click="startDownload()">Download</button>
</div>
change this :
ng-click="startDownload()"
After reading a ton of questions regarding similar problems, it emphasizes that it is not possible to save a file on the users disk, which comes from an AJAX request.
See this question on Stackoverflow.

$http in angularjs not working

I have a piece of Code in angularjs. If I hard code the value of http response it is displaying the response when I use the http method in angularjs it is not displaying. But I am getting response to that link locally. I dont know where I am wrong. Here is the code
<!DOCTYPE html>
<html>
<head>
<script script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope,$http){
$scope.test = [
{
"done": 2,
"total": 7
}
];
});
</script>
</head>
<body ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="t in test">
<span>{{t.done}}</span>
<span>{{t.total}}</span>
</div>
</body>
</html>
In Script again if i add the below code,its not displaying the values
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope,$http){
$http.get("http://localhost:8080/reports/webapi/hello/myresource2").then(function (response) {
$scope.test = response;
});
});
</script>
Try disabling web security of google chrome if you are running google chrome and run your application it will work normally.
Your problem is not with $http rather with CORS.
I've ran into this issue when I was learning angularJS.
Since AngularJS or new frameworks using AJAX extensively there is a small issue called CORS(Cross origin resource sharing) which means we can access a resource from the same domain due to security concerns.
Please refer Understanding CORS.
Web applications are served by servers however you've tried to open your html directly in browser which means you are trying to access a http resource from file protocol which is not allowed as per CORS.
You've two options to use.
Disable web security in google chrome
Run your application in a static server.
Your actual data resides in response.data. So update your scope variable accordingly,
Your controller code,
angular.module('myApp', [])
.controller('MyCtrl', function($scope, $http) {
$http.get("http://localhost:8080/reports/webapi/hello/myresource2")
.then(function (response) {
$scope.test = response.data;
});
});
Hope this solves the issue.
try to add another function for the catching of error response
$http.get("http://localhost:8080/reports/webapi/hello/myresource2").then(function (response) {
$scope.test = response;
}, function(response){
console.log(response)
});
I also went to the similar problem and solved by adding the following HTTP headers at the response of the receiving end.
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin:
You may prefer not to use the * at the end, but only the domainname of the host sending the data. Like *.example.com
But this is only feasible when you have access to the configuration of the server.
You need to add these headers in the server, not in AngularJS
Since you are sending json data through your api .You have to do like this.
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope,$http){
$http.get("http://localhost:8080/reports/webapi/hello/myresource2").then(function (response) {
$scope.test = response.data;
});
});
</script>

Ionic/Angular js Parsing JSON data from server

How to parse JSON object from server using Ionic/Angular js? This is work for me when loading json from /js folder:
var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("js/data.json") // <=== this
.then(function (response)
{
$scope.dat = response;
});
}]);
but when i load json from webserver,i got blank, this is my code :
var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("http://localhost/data.json") //<== this
.then(function (response)
{
$scope.dat = response;
});
}]);
Thanks for your help..
Analyzing what you have done so far, i suppose your data is being returned as an array from the webserver since you are getting blank with your code. So, you should assign the response[0] to $scope.dat.
var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("http://localhost/data.json") //<== this
.then(function (response)
{
$scope.dat = response[0];
});
}]);
First
Angular's $http promise response contains a few properties.
The data returned from the server would be in the data property.
From the Angular docs:
The response object has these properties:
data – {string|Object} – The response body transformed with the
`transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Also you want to make sure that the endpoint is pointing at the correct resource.
I.e if data.json is inside your application file, then the path would be path/to/data.json. This should be easy to identify, because you'll get a 404 status code with your response object.
Solution
So you might want to do something like:
var endpoint = "path/to/data.json";
$http.get(endpoint).then(function (response) {
$scope.dat = response.data;
});
One more thing
Also, if in doubt user console.debug(response); which will allow you to inspect the response object.

No 'Access-Control-Allow-Origin' error from local domain to public API

I'm trying to create an app that will retrieve the stock name, asking and buy price from Yahoo Finance API, using Restangular. I'm having a problem with accessing a public API in the local application I'm creating when I do a GET request. This is the URL with parameters that I'm sending:
http://finance.yahoo.com/d/quotes.csv?s=MSFT+GE&f=nab
Using Postman, this get request returns an array which contains the stock name, asking price and buy price of the stock. Doing the request in postman returns the desired information without any errors.
When I do this request in my local, I get the following error:
XMLHttpRequest cannot load http://finance.yahoo.com/d/quotes.csv?s=MSFT+GE&f=nab. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
The HTML code is as follows:
<html ng-app="app">
<head>
<title>Restangular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="//code.angularjs.org/1.2.27/angular-resource.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdn.rawgit.com/mgonto/restangular/master/dist/restangular.min.js"></script>
</head>
<body>
<div ng-controller="IndexCtrl" ng-cloak>
<ul>
<li ng-repeat="person in people">{{person.Name}}</li>
</ul>
</div>
And the JS:
var app = angular.module('app', ['restangular'])
.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://finance.yahoo.com/d');
});
app.controller('IndexCtrl', function($scope, Restangular) {
$scope.people = Restangular.all('quotes.csv?s=MSFT+GE&f=nab').getList();
});
I'm confused by this error because since this is a public API and POSTMAN can access it, I'd assume that the header is already present in the API server. Why would I get this error when requesting from my local?
Any help would be GREATLY appreciated.
Here's me making a JSONP request which fails because it's trying to receive a CSV file. I don't think restangular knows how to read CSV files either which is what you are attempting. I think you need to do the same thing as you are now but using the YQL API instead because I don't think this is going to work.
Anyway here's the code:
http://plnkr.co/edit/GokYqzJ0dXw86C6AM2UP?p=preview
The request (which goes through but fails due to the file type):
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'World';
$http.jsonp('http://finance.yahoo.com/d/quotes.csv', {
params: {
callback: 'JSON_CALLBACK',
s: 'MSFT GE',
f: 'nab'
}
}).success(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
})
});

Resources