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

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.

Related

$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>

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

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.

Not able to get image as json response using angularJS?

I am getting image in json response form restful api and I have to use that image in html using angularjs.
I dont know how can I use that image using angularJs
If I am trying like that "http:/api/image/id" where id is "userID". But when I write the code in angularjs I didnt get any response.I tried to debug code by using breakpoints and but it didn't go inside the function
JS Code
QAApp.controller('imgCtrl', function ($scope, $http) {
$scope.image = function (id) {
var request = $http({
method: 'GET',
url: server + 'api/image/' + id,
});
request.success(function(data, status, headers, config) {
console.log(data);
});
}
});
HTML Code
<div class="artst-pic pull-left" ng-controller="imgCtrl">
<img ng-show = "{{image(q.userID)}}" alt="" class="img-responsive" />K
</div>
Please tell me how can I use this.
From what I understand, the API directly sends you the image, not any JSON..
Then just display it like you would display any image (you don't need ajax):
JS
$scope.image = function (id) {
return server + 'api/image/' + id;
};
HTML
<img ng-src="{{image(q.userID)}}"/>
Javascript
QAApp.controller('imgCtrl', function ($scope, $http) {
$scope.image = function (id) {
$http({
method: 'GET',
url: server + 'api/image/' + id,
}).then(function(data){
$scope.imageUrl= data; // if you sure what data is you URL
})
}
});
HTML
<div class="artst-pic pull-left" ng-controller="imgCtrl">
<img ng-src="{{imageUrl}}" ng-init="image(q.userID)" alt="" class="img-responsive" />K
</div>
The Apache Roller source code has an example of using angular.js to bring in an image source: http://svn.apache.org/viewvc/roller/trunk/app/src/main/webapp/WEB-INF/jsps/editor/ThemeEdit.jsp?annotate=1621546 (line 126, with the JavaScript at the bottom of the file).

Can't perform CORS request using Angularjs

I am writing my first AngularJS app and have run into a problem with CORS in Angular. Have tried what was mentioned in this reply but still have no luck solving this.
The JS code (main.js) is as follows:
var app = angular.module("app",[]);
app.config(['$httpProvider', function($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller("AppCtrl", function ($scope, $http) {
var postData = "username=demo&password=demo";
$http.post("http://sampleurl.com/login",postData).success(function(data, status, headers, config)
{
console.log(data);
});
});
The Index.html file is:
<!DOCTYPE html>
<html>
<head>
<title>Sample Angular App</title>
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="main.js"></script>
</body>
</html>
The error I get is the following:
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have tried running this request using Ajax and it works just fine with Ajax. For some reason can't get this to work using Angular. Any idea as to what I am doing wrong here?
Thanks!
Ok. So basically after alot of tinkering around I realised that params were not getting passed using
$http.post("http://sampleurl.com/login",postData)
So I rewrote this request as follows:
$http({
url:'http://sampleurl.com/api',
method:"POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: postData
})
This got the request to go through just fine. Hope this is of help to someone else.
Cheers!
There are two things you will need to do, in the .config you need to put this:
$httpProvider.defaults.withCredentials = true;
And then on your server you need to return an an Access-Control-Allow-Origin header, it would possibly look like this:
Access-Control-Allow-Origin:http://URL_OF_SITE_YOUR_ANGULARJS_APP_IS_AT
If you want to send a CORS request 'withCredentials', you'll need to have your server reply with 'Access-Control-Allow-Origin':'http(s)://your.request.origin'. A wildcard (*) reply will be refused by most browsers for requests with credentials.
I was stuck with the same issue, then I read from this link:
http://better-inter.net/enabling-cors-in-angular-js/
and things worked like a charm :)
var myApp = angular.module('myApp', [
'myAppApiService']);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
I had the same problem before and I resolve it by adding this header:
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},

change Content-type to "application/json" POST method, RESTful API

I am new at AngularJS and I needed your help.
All I need just need is to POST my json to the API and recieve the proper response.
Here's my JSON where i don't know where to code this.
JSON
{
"userId" :"testAgent2",
"token" :"testAgent2",
"terminalInfo":"test2",
"forceLogin" :"false"
}
NOT SURE IF I'm doing this right.
CONTROLLER.JS
function UserLoginCtrl($scope, UserLoginResource) {
//Save a new userLogin
$scope.loginUser = function() {
var loggedin = false;
var uUsername = $scope.userUsername;
var uPassword = $scope.userPassword;
var uforcelogin = 'true';
UserLoginResource.save();
}
}
SERVICES.JS
angular.module('UserLoginModule', ['ngResource'])
.factory('UserLoginResource', function($resource, $http) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.post["Content-Type"] = "application/json"; //NOT WORKING
return $resource('http://123.123.123.123\\:1234/SOME/LOCATION/THERE', {}, {
save: {
method:'POST',
headers: [{'Content-Type': 'application/json'}]
} //NOT WORKING EITHER
});
});
INDEX.HTML
<html ng-app>
<head>
<script src="js/lib/angular/angular.js"></script>
<script src="js/lib/angular/angular-resource.js"></script>
</head>
<body ng-controller="UserLoginCtrl">
<form class="form-horizontal" name="form-horizontal" ng-submit="loginUser();">
<div class="button-login">
<!-- start: button-login -->
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</body>
</html>
I kept on getting a response like Unsupported Media Type. I don't know, what else to do.
Assuming you are able to use one of the more recent "unstable" releases, the correct syntax to change the header is.
app.factory('BarService', function ($resource) {
var BarService = $resource('/foo/api/bars/:id', {}, {
'delete': {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
}
});
return BarService;
});
I find the $resource service is a tremendously powerful tool for building applications and has matured to a point that you do not need to fall back to $http as much. Plus its active record like patterns are damn convenient.
Posting a JSON object is quite easy in Angular. All you need to do is the following:
Create a Javascript Object
I'll use your exact properties from your code.
var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";
Post the object to the API
To post an object to an API you merely need a simple $http.post function. See below:
$http.post("/path/to/api/", postObject).success(function(data){
//Callback function here.
//"data" is the response from the server.
});
Since JSON is the default method of posting to an API, there's no need to reset that. See this link on $http shortcuts for more information.
With regards to your code specifically, try changing your save method to include this simple post method.
The right way to set 'Content-Type': 'application/json' is setting a transformRequest function for the save action.
angular.module('NoteWrangler')
.factory('NoteNgResource', function NoteNgResourceFactory($resource) {
// https://docs.angularjs.org/api/ngResource/service/$resource
return $resource("./php/notes/:id", {}, {
save : { // redefine save action defaults
method : 'POST',
url : "./php/notes", // I dont want the id in the url
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
}
}
});
});
It seems there isn't a method to clear query parameters, the request will have both...

Resources