I'm not sure why when i print the json file on a html page works, also from a button calling a function, but not inside of the javascript file.
This a problem because i need to sort the data in the json file before displaying it from in the web page, i can't make it work. i tried using this solution https://stackoverflow.com/a/15463124/2796268,
but the console say
jsonDat is not defined
my code:
$scope.init = function () {
console.log("init");
$http.get('json/file.json') .success(function(data) {
$scope.jsonDat = res.data;
})
.error(function(data,status,error,config){
$scope.jsonDat = [{heading:"Error",description:"Could not load json data"}];
});
console.log(jsonDat);
};
How i can process the json data before the page loads or when the page is loading?
You can process the data when it is returned from $http, like so:
$scope.init = function () {
$http.get('json/file.json').success(function(data) {
//---- SORT HERE ----
$scope.jsonDat = mySortFunction(data);
});
};
Try this :
$scope.init = function() {
console.log("init");
$http.get('json/file.json').success(function(data) {
$scope.jsonDat = data;
console.log($scope.jsonDat);
})
.error(function(data, status, error, config) {
$scope.jsonDat = [{
heading: "Error",
description: "Could not load json data"
}];
console.log($scope.jsonDat);
});
};
In success you have data but you try get from res.data. When you use success then it is not response with data but only your data.
I thought you wanna sort some JSON file then display it in HTML page . So My Idea is get that JSON file (you tried)
$http.get('json/file.json') .success(function(data) {
$scope.jsonDat = data.res;
console.log('Checking the result',angular.toJson($scope.jsonDat));
})
But putting your result in
$scope.jsonDat = data.res;
eg,
sortService.sortJsn = data.res;
$scope.jsonDat instead create angular service pour your data there then you can access those data any where in your controller sort it also show it in HTML.
Related
I am trying to use json using API to retrieve data on a Google Map in AngularJS.
This is my code in Angular:
$scope.loadData = function () {
var map_info = {
'ApiKey': '1iVuQy3FGK39d51',
'ProjectId': '11'
};
var url = "http://localhost:63411/api/clientportal/?action=mapjson";
return $http.post(url, map_info).then(function (response) {
return response.data.MapData;
});
};
But, when I run the code, it shown 'Cross-Origin Reuest Block' error.
Then, I search from the internet about this error, I come out with a solution to change $http.post to $http.jsonp.
$scope.loadData = function () {
var map_info = {
'ApiKey': '1iVuQy3FGK39d51',
'ProjectId': '11'
};
var url = "http://localhost:63411/api/clientportal/?action=mapjson";
return $http.jsonp(url, map_info).then(function (response) {
return response.data.MapData;
});
};
It does go to the URL, however the Request Body is empty.
Since I created the API using C#, the 'Request.InputStream' is null.
string jsonPosted = new StreamReader(Request.InputStream).ReadToEnd();
So the 'jsonPosted' is null.
I did try on Postman, and it works. But not in Angular.
How do I send the Request Body properly?
I want the 'ApiKey' and 'ProjectId' to be included on Request Body.
Thank You.
I have my JSON file as follows
{
"colorsArray":[{
"colorName":"red",
"hexValue":"#f00"
},
{
"colorName":"green",
"hexValue":"#0f0"
},
{
"colorName":"blue",
"hexValue":"#00f"
},
{
"colorName":"cyan",
"hexValue":"#0ff"
},
{
"colorName":"magenta",
"hexValue":"#f0f"
},
{
"colorName":"yellow",
"hexValue":"#ff0"
},
{
"colorName":"black",
"hexValue":"#000"
}
]}
And my js file for the particular as follows.....I'm reading the json file here by using $http.get functionality
var app = angular.module('app', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get('tags.json');
};
});
How will I be able to get only colorName as parsed element when the JSON file referred externally in $http.get using AngularJS?
you can't query the json file on the fly when the request made to json file. One way and most efficient way is to send http call with query as parameter to backend service method and execute and return the result from server side.
Other way is filter the result from the client side. This way all the json data will return as the response and then need to filter the relevant data from the controller '
$scope.loadTags = function(query) {
return $http.get('tags.jon').then(function(response) {
var data = response.data.map(function(obj) {
return obj.colorName;
})
return data;
})
};
Here is my working code (in Angular):
var url ="https://api.flickr.com/services/rest/?method=flickr.photos.search&
api_key=c4e2f731926eefa6fe1d3e9c2c9f9449&tags=coffee&format=json&jsoncallback=JSON_CALLBACK";
$http.jsonp(url).then(function(response) {
console.log(response.data);},function(){console.log('Error retrieving JSON data')}
);
However I do not know how to send totagsa variable's value and not just writing coffee or chocolate. Is there a better way to organize all this information (api_key, format, tags) in an object and append it to url?
You can use config.params object to set tags GET parameter:
var url = "https://api.flickr.com/services/rest/?api_key=c4e2f731926eefa6fe1d3e9c2c9f9449&method=flickr.photos.search&format=json&jsoncallback=JSON_CALLBACK";
$scope.tags = 'coffee';
$http.jsonp(url, {
params: { tags: $scope.tags }
})
.then(function(response) {
console.log(response.data);
}, function() {
console.log('Error retrieving JSON data')
});
I am trying to build a simple app using Angular JS. Here I have two html files (Login.html & Dashboard.html). when I run the Login.html it works well And on the successful log in I need to show the user dashboard with the json data populated(from server) at Login time.
here is my code: (main.js)
var app = angular.module('NovaSchedular', []);
app.factory('MyService', function()
{
var savedData = {}
function set(data)
{
savedData = data;
}
function get()
{
return savedData;
}
return {
set: set,
get: get
}
});
function LoginController($scope,$http,MyService,$location)
{
$scope.login = function(str) {
console.log(".......... login called......");
var validEmail=validateEmail(email.value);
if(validEmail && password.value != ""){
$http.post('./nova/TaskManager/public/user/login?email='+email.value+'&password='+password.value).success(function(data, status)
{
console.log(data);
var result=data.response;
console.log(result);
if (result=="success")
{
$scope.userId=data.user_id;
$scope.email=data.email;
$scope.Name=data.name;
$scope.password=data.password;
$scope.Type=data.type;
console.log("........"+$scope.userId);
console.log("........"+$scope.email);
console.log("........"+$scope.Name);
console.log("........"+$scope.password);
console.log("........"+$scope.Type);
MyService.set(data);
console.log(data);
alert(data.message);
window.location.href='./Dashboard.html';
//$location.path('./Dashboard.html', data);
}
else
alert(data.message);
});
}
}
}
function DashboardController($scope,$http,MyService)
{
$scope.userInfo = MyService.get();
}
here after LOGIN successfully, I am getting the server response (json data) under the LoginController well. Now, further I need these data to be available on the Dashboard page so that dashboard would populate with the respective user data.
I am trying this by using:
window.location.href='./Dashboard.html';
//$location.path('./Dashboard.html', data);
but it didn't work for me. It's redirecting to the Dashboard.html well, but doesn't containing the data what I need to pass from the LoginController to the DashboardController. so, that it would available for the Dashboard.html page.
while seeing at the console for the Dashboard.html, it's empty json is showing there.
Don't know what's missing. why it's not passing the data.
Any suggestion would be appreciated.
try this controller code :
app.controller('LoginController' function($scope,$http,MyService,$location)
{
$scope.login = function(credential) {
console.log(".......... login called......");
var validEmail=validateEmail(credential.email);
if(validEmail && credential.password!= ""){
MyService.login(credential);
}
}
});
and this:
app.controller('DashboardController',function($scope,$http,MyService)
{
$scope.userInfo = MyService.getDashboardData();
});
MyService.js:
var app = angular.module('NovaSchedular', []);
app.factory('MyService', function()
{
var dashboardData;
var obj={
login:function(credential){
$http.post('./nova/TaskManager/public/user/login?email='+credential.email+'&password='+credential.password).success(function(data, status, headers) {
dashboardData=data;
window.location.href='./Dashboard.html';
})
.error(function(data, status, headers, config) {
console.error('error in loading');
});
},
getDashboardData:function(){
return dashboardData;
}
}
return {
login:obj.login,
getDashboardData:obj.getDashboardData
}
});
In my Angular / Rails app, I am uploading a spreadsheet using the angular-file-upload gem. https://github.com/danialfarid/angular-file-upload
I pass the spreadsheet to the Rails backend, and it processes the data and returns a JSON array.
The Angular code that passes the file up is this:
$scope.submitForm = function () {
console.log('submit upload2');
return $scope.upload = $upload.upload({
url: '/api/batches/spreadsheet_upload.json',
data: {
id: 99,
assembly: "xy"
},
file: $scope.file
}).success(data, status, headers, config)(function () {
debugger
$scope.selector.tabledata = data;
$scope.uploaded = true;
});
};
Rails accepts the file and processes it. I am trying to return it with render json: {data: spreadsheet_data}
def spreadsheet_upload
Rails.logger.debug("here params: #{params}")
spreadsheet = nil
case File.extname(params[:file].original_filename)
when '.csv' then spreadsheet = Roo::CSV.new(params[:file].path)
when '.xls' then spreadsheet = Roo::Excel.new(params[:file].path, nil, :ignore)
when '.xlsx' then spreadsheet = Roo::Excelx.new(params[:file].path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
spreadsheet_header = spreadsheet.row(1)
spreadsheet_data = []
(2..spreadsheet.last_row).each do |i|
row = Hash[[spreadsheet_header, spreadsheet.row(i)].transpose]
spreadsheet_data.push(row)
end
render json: {data: spreadsheet_data}
end
The network tab in Chrome shows me the data has been returned from the Rails server, but Angular doesn't seem to know what to do with it.
ReferenceError: data is not defined
at Object.$scope.submitForm (http://0.0.0.0:3000/assets/controllers/DesignViewCtrl.js?body=1:203:18)
at http://0.0.0.0:3000/assets/lib/angular.min.js?body=1:1936:30
at http://0.0.0.0:3000/assets/lib/angular.min.js?body=1:4127:15
at Object.e.$eval (http://0.0.0.0:3000/assets/lib/angular.min.js?body=1:2432:24)
at Object.e.$apply (http://0.0.0.0:3000/assets/lib/angular.min.js?body=1:2439:40)
at HTMLFormElement.<anonymous> (http://0.0.0.0:3000/assets/lib/angular.min.js?body=1:4126:15)
at HTMLFormElement.jQuery.event.dispatch (http://0.0.0.0:3000/assets/jquery.js?body=1:2940:98)
at HTMLFormElement.elemData.handle (http://0.0.0.0:3000/assets/jquery.js?body=1:2750:123)
Returned data in the network tab
{"data":[{"chrom":4.0,"chrom_start":55593607.0,"chrom_end":55593607.0}, {"chrom":"4","chrom_start":55593609.0,"chrom_end":55593617.0},{"chrom":"6","chrom_start":133105152.0,"chrom_end":133105152.0}]}
I have also tried changing to a response, but this also did not work.
}).success(resp)(function () {
$scope.selector.tabledata = resp.data;
$scope.uploaded = true;
});
Not sure but the structure on the success that i have seen looks like
.success(function(data, status, headers, config) {
$scope.selector.tabledata = data;
$scope.uploaded = true;
});