Setting up the Header Using Http to get the Json file - json

I do have a working table using JSON and angular, I set up my $http header to get the Json in the particular .api, I run it but nothings appear in getting my Json file in the $Http.get, I would like to ask if this is a valid header, I mean is there something wrong with my delimeter?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script type="text/javascript">
var myTable=angular.module('myTable',[]);
myTable.controller('tableCtrl',function($scope,$http){
$http.get ("http://staging.api.sample.com/events.json", {header: {Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'}}); .success(function(response) {
debugger
$scope.members=response.events;
$scope.totals = response.paging;
});
});

Remember about correct style guide. It should help you. Also check this link https://github.com/johnpapa/angular-styleguide/
(function {
'use strict';
angular
.module('myTable', [])
.controller('tableCtrl', tableCtrl);
tableCtrl.$inject = ['$scope', '$http'];
function tableCtrl($scope, $http) {
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}).then(function(response.data) {
$scope.members = response.data.events;
$scope.totals = response.data.paging;
}).catch(function(error) {
});
});
}());
This query is wrong:
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}
You can pass parametes by get building query like this one:
$http.get("http://staging.api.sample.com/customer/1") or
$http.get("http://staging.api.sample.com/customer/" + some_param). If you would like to send some object to you API you should use POST. For example:
$http.post("http://staging.api.sample.com/events.json", {object});

Related

How can I send requests to JSON?

I'm coding a mobile application with ionic. I have to get a data (daily changing data) from a web page with JSON, but I want to get old data too. For example:
data.json?date=2016-11-10
data.json?data=2016-12-10
How can I send request to JSON?
To send data from PHP, once you get your data from the database, the array will apply json_encode($array); and to return you put return json_encode ($ array);
Try this!
var date = '2016-11-10';
$http({
method: 'GET',
url: data.php,
params: {date: date},
dataType: "json",
contentType: "application/json"
}).then(function(response) {
});
The question is confusing, so I'm not sure how to answer. If you are having trouble formatting a request to a REST service, you will need to find out how the service expects the date to be formatted in your field-value pair i.e:
date=2016/11/10 or date=20161110
If those don't work, this answer may help The "right" JSON date format
However, if you are actually wondering how to serialize a date in JSON, this link may help http://www.newtonsoft.com/json/help/html/datesinjson.htm
I prefer to use services for ajax requests.
Create a Service
//Service
(function() {
'use strict';
angular
.module('appName')
.factory('appAjaxSvc', appAjaxSvc);
appAjaxSvc.$inject = ['$http', '$log', '$q'];
/* #ngInject */
function appAjaxSvc($http, $log, $q) {
return {
getData:function (date){
//Create a promise using promise library
var deferred = $q.defer();
$http({
method: 'GET',
url:'/url?date='+date
}).
success(function(data, status, headers,config){
deferred.resolve(data);
}).
error(function(data, status, headers,config){
deferred.reject(status);
});
return deferred.promise;
},
};
}
})();
Then Use it in Controller
(function() {
angular
.module('appName')
.controller('appCtrl', appCtrl);
appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];
/* #ngInject */
function appCtrl($scope, $stateParams, appAjaxSvc) {
var vm = this;
vm.title = 'appCtrl';
activate();
////////////////
function activate() {
appAjaxSvc.getData(date).then(function(response) {
//do something
}, function(error) {
alert(error)
});
}
}
})();

Angular factory does not return array of objects but a single object

I am new to angular and I am trying to load a CSV list inside a factory and then convert it to json. I am using Papaparse (CSV to json library) inside the factory. When I console log the factory I get the array of objects which is exactly what I want but when I pass it inside my controller I get a single object which holds all the data.
This is my factory
(function() {
var app = angular.module('test');
app.factory('testFactory', ['$http', function($http) {
var url = 'my-list.csv';
var getContact = function() {
return $http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
return results.data;
}
});
});
};
return {
getContact: getContact
};
}]);
}());
And this is my controller
(function() {
var app = angular.module('test');
app.controller('testCtrl', ['$scope', 'testFactory', function($scope, testFactory) {
testFactory.getContact().then(function(data) {
$scope.contacts = data;
console.log(data);
});
}]);
}());
I want be able to do something like this inside my view
{{ contact.firstname }}
The issue is the order of resolution. Inspecting the console statements shows that you're assigning $scope.contacts to the resolution of the $http.get promise, and not the actual parsing.
Instead of returning the $http.get promise, return a deferred promise and resolve at the end of parsing:
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
parsePromise.resolve(results.data);
}
});
});
return parsePromise.promise;
See working demo here.
Update: As per the comments, you could use .then to chain promises instead of creating a new deferred. The plunkr has both, you can use the changelog to toggle methods.

Need Help Reading JSON object from a URL in a HTML

I am trying to create a website in where I can get a particular json object from a url and then display it on the website. The field that I am trying to display is UV_INDEX out of three fields. Nothing is being printed out. I don't even know if it is getting the json object.
<!DOCTYPE html>
<html>
<body>
<h2>EPA </h2>
<p id="demo"></p>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON').then(function(data) {
document.getElementById('UV_INDEX').innerHtml=json.result;
alert('Your Json result is: ' + json.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>
I added a third-party chrome extenstion for CORS issue. But I get this error
Uncaught (in promise) ReferenceError: json is not definedmessage: "json is not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
You can try using a Ajax plugin to make CORS request where the CORS headers are not being served from service.
Add Jquery library and add your installed CORS ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
Now you can make cross origin request by just adding crossOrigin: true in your Ajax:
E.g.
$.ajax({
crossOrigin: true,
url: "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON/",
success: function(data) {
console.log(data);
}
});
You can try putting the same URL in the below demo page to receive the Json data.
See live demo.

How is possible to load some setting from .json file before angular app starts

i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});

Fetching data from a JSON object (from a given API) in AngulaJS

I have the following code to present data from a link (API) as suggestion for an autocomplete box. Although it is working for one link and not the other. I observed that data format for both are different, modified my code accordingly but it is still not helpful.
.js file:
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.jsonp("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response[0].description;
});
};
}
HTML file:
<input type="text" id="depn" ng-model="formdata.department"
typeahead="suggestion.description for suggestion in cities($viewValue)"
placeholder="department" class="form-control">
If you replace the cities function with this one,
$scope.cities = function (cityName) {
return $http.jsonp("http://gd.geobytes.com/AutoCompleteCity?callback=JSON_CALLBACK &filter=US&q=" + cityName).then(function (response) {
return response.data;
});
};``
Even after I changed my code jsonP request to .get, it is still not working
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").success(function(data) {
return data[0].description;
});
};
}
It is working fine.
Is there a problem with my code, or a back end server issue?
Change your cities function to use the data property of the response in your .then (that's how you'll access the response from a resolved HttpPromise):
var plunker= angular.module('plunker', ['ui.bootstrap', 'ngGrid']);
function TypeaheadCtrl($scope, $window, $http, limitToFilter) {
$scope.cities = function (cityName) {
return $http.get("http://mtapi.azurewebsites.net/api/institute").then(function (response) {
return response.data[0].description;
});
};
EDIT
Even making that code change won't solve your problem. This url does not support cross-origin requests, so you either need to host your angularjs app on the same domain and use a plain $http.get instead of $http.jsonp, or this url needs to support JSONP requests (the content-type of the response from this url is application/json. For JSONP to work it should be application/javascript).
I figured it out lately. Apart from the problem at back end there were issues in this code as well. I was returning the promise, but promise was never resolved to return the value also I was trying to return a string, whereas I should return array of strings. Here's the change:
$scope.aap = result.data;
var res = [];
res.push($scope.aap[0].Description);
return res;