Load JSON file from the file name passed in the parameter - angularjs

I want to read data from json file. I passed the file name as parameter and try to load data from data/{{filename}}.json
But it cannot found the file and shows this error message
data/%7B%7Bfilename%7D%7D.json 404 (Not Found)
Here is my function
$scope.getSelectedCategoryData=function(fileName){
$http.get('data/{{filename}}.json')
.success(function (data) {
$scope.selectedCategoryData = data.GetAllData;
})
.error(function (data, status, headers, config) {
})
}
And my question is how can I load the file from the value passed in parameter. Is there any way like this?
<img ng-src="img/{{image}}.png"/>

The mustache notation is meant to use in html and not in Javascript. You have to follow the standard Javascript string concatenation. The below example will work for you.
$scope.getSelectedCategoryData=function(fileName){
var filePath= 'data/' + fileName +'.json';
$http.get(filePath)
.success(function (data) {
$scope.selectedCategoryData = data.GetAllData;
$scope.image=data.GetAllData.image //image path
})
.error(function (data, status, headers, config) {
})
}
Then you can use:
<img ng-src="img/{{image}}.png"/>

Related

Give the more than one parameters in http request angularjs

My Laravel route is :
Route::get('/get_event_history/{data}/{date}', 'HomeController#GetEvents')->name('get_event_history');
and I wanted to pass two routes. I am doing like this:
$scope.HistoryEventClick=function(imei,date){
var Indata = {'data': imei, 'date': date };
$http.get('/get_event_history/',params: Indata).success(function (data, status, headers, config){
console.log("Event Data from the query",data.data);
}).error(function (data, status, headers, config) {
//alert(status)
});
}
Its not working and gives error route not found
You may need to change to this:
$http.get(`/get_event_history/${imei}/${date}`).......
$http.get('/get_event_history/'+$routeParams.imei +'/date/'+ $routeParams.date)

Angularjs - 500 (Internal Server Error) on $http Post

I am new to Ionic and angular. I am building a sample with ionic framework using angular.js. I want to call WebApi through $http post method. I checked this(ionic-proxy-example) solution and I am trying to implement the same using my api. When I call the api provided in above example in my sample project, I get the records but its not working with my api. It throws 500 internal error.
Here is my app.js
angular.module('myApp', ['myApp.controllers', 'myApp.services'])
.constant('ApiEndpoint', {url: 'http://localhost:8100/api'})
Services.js
angular.module('myApp.services', [])
.factory('Api', function($http, $q, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint)
var getApiData = function() {
var q = $q.defer();
var data = {
Gameweek_ID: '179',
Vender_ID: '1',
Language:'en'
};
var config = {
headers : {
"Content-Type": "application/json; charset = utf-8;"
}
};
$http.post(ApiEndpoint.url, data, config)
.success(function (data, status, headers, config) {
// $scope.PostDataResponse = data;
alert('success');
console.debug("response :" + data);
q.resolve(data);
})
.error(function (data, status, header, config) {
// $scope.ResponseDetails = "Data: " + data +
alert('error');
console.debug("error :" + data);
q.reject(data);
});
return q.promise;
}
return {getApiData: getApiData};
})
controllers.js
angular.module('myApp.controllers', [])
.controller('Hello', function($scope, Api) {
$scope.employees = null;
Api.getApiData()
.then(function(result)
{console.log("result is here");
jsonresponse = result.data;
$scope.employees = jsonresponse;}
)
});
And Ionic.Project File
{
"name": "Multilingual",
"app_id": "4b076e44",
"proxies": [
{
"path": "/api",
"proxyUrl": ""
}
]}
I am trying to understand the problem and checked multiple methods to call the api. Surprisingly, it works with ajax post call without any CORS errors. As I am using Angular, I am trying to get this done through $http post. I feel it is some minor issue but I am not able to figure out. Will be grateful for solutions. Thank you.
You've set the content type to json so the sever is expecting a json string but isn't receiving a properly formatted json string as you're sending through an object and hence the error.
Where you have $http.post(ApiEndpoint.url, data, config) change it to $http.post(ApiEndpoint.url, JSON.stringify(data), config).
If that doesn't work, change your content type to application/x-www-form-urlencoded and update this line $http.post(ApiEndpoint.url, data, config) to $http.post(ApiEndpoint.url, $httpParamSerializer(data), config) , don't forget to inject the $httpParamSerializer function.
The problem is that you are sending a POST with $http.post request instead of a GET request with $http.get
Try as below-
$http({
url: ApiEndpoint.url,
method: "POST",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).Success(..rest code goes here..)
In WebAPI, when we pass more than one object in POST method, we get 500 internal error and hence we use ViewModel in such scenarios(talking about asp.net MVC).

How to post a request and download file to disk with angular?

In angular, I want to download a text file containing a csv of userdata. Usually I have a form with a post action, but I want the user to stay on the same page, but return the csv data without any page referesh. The following is my post command:
$http({
url: "api/getUserData",
method: "POST",
data:{user_id:app.user_id}
}).success(function(data, status, headers, config) {
// data gets returned here
}).error(function(data, status, headers, config) {
$scope.status = status;
});
My problem is, the "data" that comes back from the post is a csv file. how can I get the data to actually "download" to the user's computer instead of living in the javascript? Is this even possible?
Here is the link to solution. It uses HTML5 FileSaver API to save the file as BLOB
You can do this :
Create temporary anchor ,
encode, your data & name your file using download attribute,
and then, fire a click event on it.
finally, remove the inserted element .
$http({
url: "api/getUserData",
method: "POST",
data:{user_id:app.user_id}
}).success(function(data, status, headers, config) {
// data gets returned here
var anchor = angular.element('<a/>');
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'myFileName.csv'
})[0].click(); // fire a click event.
anchor.remove(); // Clean it now ...
}).error(function(data, status, headers, config) {
$scope.status = status;
});

How do I send an image file for download from Node backend to Angular frontend?

I have an app with an Express backend, and angular frontend. I am trying to create a file download link for image files, but I am running into problems sending the file from express to angular. My angular looks like this...
scope.download = function(file){
http({method:'GET', url:'/get_download/' + file.id}).
success(function(data, status, headers, config) {
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment;charset=utf-8,' + encodeURIComponent(data),
target: '_self',
download: file.name
})[0].click();
}).
error(function(data, status, headers, config) {
console.log("THERE WAS AN ERROR");
});
}
I have tried several different things on the express side each of which are producing different errors.
First I tried the following...
res.download("my_file_path", "my_file_name", function (err) {
if (err) {
console.log("ERROR");
console.log(err);
}
});
And got this error...
path.js:360
throw new TypeError('Arguments to path.join must be strings');
^
TypeError: Arguments to path.join must be strings
Then I tried...
fs.readFile("my_file_path", function(err, data) {
res.writeHead(200, { 'Content-disposition': 'attachment' });
res.end(data);
});
Which downloaded the file, but it got corrupted along the way, and would not open.
Any suggestions would be appreciated.

How can set a script to run after all photos have loaded?

I have have spent hours trying all of the different methods given online but nothing works. I just simply want to load a script to run after all images have loaded. Is there something about Angular that won't allow me to do this? I'm using $routeProvider:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
// this doesn't work
$(window).load(function() {
myScript();
});
})
.error(function (data, status, headers, config) { $scope.status = status; });
}
}
}
};
By the way, I'm not getting any errors in the console.
It seems to me that the http POST call retrieves the photos. And I am suppose that myScript is a function. So why not try this:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
myScript();
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
}
}
};
since the myScript function only runs after the POST succeeds. I am supposing that the data refers to the actual image data.
I don't know if I really understood what type of data you are trying to get, but I think you could try with promises
$http in Angular already return a promise wrapped in .success or .error, but you can also use the .then() callback like with every other promise
So if the problem is to wait for the success() callback to be finished you could do something this way, replacing it by several then() :
$http.post(...).then(
//function which will wait for the data to be downloaded
//here you can alter data, check some values etc...
).then(
//the script for what you want after
myScript();
);
I made a little fiddle to explain : http://jsfiddle.net/Kh2sa/2/
It simulates a long response time with $timeout, so you have to wait 3 secondes to see your modified data, which remains in its initial state until you call the myScript() function
AFAIK, Angular does not provide a way to inform us when images have finished loading.
You will need to write your own directive for this. The directive would wrap the necessary JavaScript/jQuery code that would detect the finished loading condition for one or more images.
jQuery callback on image load (even when the image is cached) and https://github.com/desandro/imagesloaded might help.

Resources