Read from json file angularjs - angularjs

I had json file that I want to fetch data from it using angularjs 1.6 and I wrote some code in controller. I wanna sort out the properties names of objects in console like this:
['web-desktop','android','ios']
The problem that it returned array of undefined values and wanna to figure it out.
There is json file "data.json":
[
{
"platform": "web-desktop",
"cdn": 4.3673292887e+10,
"p2p": 5.667683381e+09,
"total": 4.9340976268e+10,
"upload": 5.774321084e+09,
"percentage": 12,
"viewers": 1,
"maxViewers": 10,
"averageViewers": 1.5725853094274147,
"trafficPercentage": 69.49888073943228,
"live": "unknown"
},
{
"platform": "android",
"cdn": 1.7035777808e+10,
"p2p": 1.526916976e+09,
"total": 1.8562694784e+10,
"upload": 2.753179184e+09,
"percentage": 9,
"viewers": 1,
"maxViewers": 12,
"averageViewers": 1.416065911431514,
"trafficPercentage": 26.14635154335973,
"live": "unknown"
},
{
"platform": "ios",
"cdn": 2.994960132e+09,
"p2p": 9.6722616e+07,
"total": 3.091682748e+09,
"upload": 3.3788984e+07,
"percentage": 4,
"viewers": 1,
"maxViewers": 3,
"averageViewers": 1.152542372881356,
"trafficPercentage": 4.354767717207995,
"live": "unknown"
}
]
And here is my controller:
'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);
function MainController ($scope, $http) {
// REQUEST OPTIONS USING GET METHOD.
var request = {
method: 'get',
url: 'data.json',
dataType: 'json',
contentType: "application/json"
};
$scope.arrSeries = new Array;
$http(request)
.then(function onSuccess(jsonData) {
angular.forEach(jsonData, function (item) {
$scope.arrSeries.push(item.platform);
});
console.log($scope.arrSeries);
}).catch(function onError(request) {
console.log("not found");
});
}
It returns in console:
(6) [undefined, undefined, undefined, undefined, undefined, undefined]
Where is the trick?

You need to loop through items in jsonData.data not jsonData directly, like this:
$http(request)
.then(function onSuccess(jsonData) {
angular.forEach(jsonData.data, function (item) {
$scope.arrSeries.push(item.platform);
});
This is because jsonData is the response object that's returned, which looks like this:
response = {
config: {method: "GET", transformRequest: Array(1), transformResponse: Array(1), paramSerializer: ƒ, jsonpCallbackParam: "callback", …},
data: (3) [{…}, {…}, {…}],
headers: ƒ (d),
status: 200,
statusText: "OK",
xhrStatus: "complete"
}
So if you loop on the response directly, you'll loop 6 time trying to get platform from each item (which isn't there). Hence the result you got.
The data that your request returns sits in response.data
response = {
...
data: (3) [{…}, {…}, {…}],
...
}
Hope that helps.

Related

React js Axios call

I'm fairly to new to React and I can't seem to be able to successfully make a call to an external API using Axios.
The guidelines of the external API are:
Request (in case we know all the parameters)
{
"service": "login",
"username": "john",
"password":"aitis",
"appId": "2001",
"COMPANY": "1000",
"BRANCH": "1000",
"MODULE": "0",
"REFID": "1",
---- optional ---
"LOGINDATE": "2017-12-31 13:59:59",
"TIMEZONEOFFSET": -120
}
Response
{
"success": true,
"clientID": "Wj8Te8EqWghDM......... .....wYGtzlyc1At%2bPrG8t"
}
My code is:
componentDidMount() {
axios.get('http://...serverurl....', {
params: {
service: 'login',
username: 'john',
password: 'aitis',
appID: '2001',
company: '1000',
branch: '1000',
module: '0',
refid: '1'
},
headers: {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
}
})
.then(response => console.log(response));
}
Instead of getting the clientID response I get this:
Response
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
data:
success: false
errorcode: 0
error: "JSON Object must begin with "{" at character 2 of service=login&username=john&password=aitis&appID=2001&Company=1000&Branch=1000&Module=0&Refid=1 JSON Syntax Error : at charact↵
error on character : 2"
__proto__: Object
status: 200
statusText: ""
...
Is something wrong with my call?
Thanks in advance.
If want to send a GET request with those params set those in URL
const URL = `${baseURL}/url?service=login&username=jhon&password=aitis&appID=2001&company=1000&branch=1000&module=0&refid=1`;
axios.get(URL).then(response => console.log(response));
I figured it out. I had to use axios.post instead of axios.get.
Thank you all very much

How to Read the value of below json in controller.js. As i have to set the value in controller.js only

Let Me know how to access the value of response by looking to the below json data
Login Controller
app.controller('loginController', function($scope,$http, $location,
$rootScope,$window) {
$scope.submit = function(){
$rootScope.userName=$scope.username;
var username=$scope.username;
var password=$scope.password;
$http({
method: 'POST',
url: 'http://localhost:8082/APIGateway/APILoginService/login',
data: jsonData,
headers : {
'Content-Type': 'application/json',
'Orgkey': 'S2lyYW5fcmFqYWdvcGFs'
}
})
.then(function successCallback(response) {
if(response.data.code=="Invalid loginId or password" || response.data.message=="Invalid loginId or password"){
$scope.errorMessage = 'Invalid LoginId/Password';
} else {
$rootScope.loggedIn=true;
$rootScope.userName = response.data.APIUserData;
$rootScope.roleName=response.data.roleName;
}
},
};
});
This is The json data.
{
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
}
I am facing problem because of APIUserData. If i remove it i can easily access the value. can anybody help me in fixing the issue
APIUserData is an array. You could do something like this:
var myResponse = {
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
};
var roleID = myResponse.APIUserData[0].roleID;

UI-Grid not displaying JSON data?

I have what I think is the correct accessor syntax for binding my UI-Grid control, I don't get any errors or any data. I just get a warning about Mutating the prototype.
My json data structure is like this:
{
"records": [
{
"acctIdInfo": {
"acctId": "257905480",
"acctCode": "ABC10101102",
"acctName": "BIG CORPORATION",
"acctRole": [
"C"
]
},
"acctNameAddr": {
"addressLine": [
"7280 JAMISON ST"
],
"cityName": "VANCOUVER",
"stateCd": "US-WA",
"countryCd": "US",
"postalCd": "97979"
}
}
]
}
The code in my AngularJS controller to bind is:
var app = angular.module('app', ['ui.grid', 'ngResource'])
.factory('jsonDataFactory', function ($resource) {
return {
custData: $resource('data.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
}),
};
});
app.controller('MainCtrl', ['$scope','$resource','jsonDataFactory', function ($scope,$resource, jsonDataFactory) {
$scope.gridOptions = {
enableRowSelection: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35
};
$scope.gridOptions.columnDefs = [
{ name: 'acctIdInfo.acctId' },
{ name: 'acctIdInfo.acctCode'},
{ name: 'acctIdInfo.acctName'},
{ name: 'acctNameAddr.addressLine' }
];
$scope.gridOptions.data = jsonDataFactory.custData.query().records;
$scope.CustomerData = [];
$scope.CustomerData = jsonDataFactory.custData.query();
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
}]);
Here is my plnk of what I tried -
I think I'm close...
Do assign a data to ui-grid data source once ajax call response comes back. I assumed that you had used $resource, so you can have promise over it to attach callback function.
jsonDataFactory.custData.query().$promise.then(function(response){
$scope.CustomerData = response;
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
});

How to post an array object in ajax call in angularjs

I have below JSON response, I have to post that in my ajax call but i don't know how to do that.
JSON response:
{
"iASensorTypePresetRequest": [{
"sensorPresetTypeId": "1",
"min": "30",
"max": "50"
}, {
"sensorPresetTypeId": "3",
"min": "1",
"max": "200"
}, {
"sensorPresetTypeId": "5",
"min": "true",
"max": "NA"
}, {
"sensorPresetTypeId": "6",
"min": "false",
"max": "NA"
}
]
}
I have below code:
var formData = $scope.PresetObject;
var reqHeader = {
method: 'POST',
url: getAPI_URL('221') + $scope.selectedUseCase,
data: formData
};
ajaxService.AjaxCall(SuccessFunction, ErrorFunction, reqHeader);
I have posted objects but i have to post that in array that is 'iASensorTypePresetRequest'
I have written service 'ajaxService' and written functions in it 'SuccessFunction' in success function i have called $http service also I have written error function and calling 'AjaxCall' function of service from controller.
My question is How to post an array containing objects in ajax call?
I use the $http service when communicating with the backend. I recommend placing all your backend connectivity into a service. I call mine datacontext.
this is the link to the $http documentation
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
If your api is RESTful you can use the $resource factory.

$resource and get array

I have an API which returns data with the following form (using tastypie):
{"meta":{
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 4},
"objects": [
{
"id": 1,
"name": "name1",
"resource_uri": "/api/v1/operator/1",
"short_name": "NA1"
},
{
"id": 2,
"name": "name2",
"resource_uri": "/api/v1/operator/2",
"short_name": "NA2"
},
...
]
}
So I thought that to have my resource working, I should have used:
var Operator = $resource('http://127.0.0.1:8080\:8080/api/v1/operator/:operatorId',
{operatorId:'#id'},
{
query: {
method: 'GET',
transformResponse: function (data) {
console.log(JSON.parse(data).objects)
return JSON.parse(data).objects;
},
isArray: true
}
});
But when I set isArray to true : I got the following error:
TypeError: Object #<g> has no method 'push'
If I set isArray to false, I have no error but my object also contains all meta datas for this request...
Not sure I understand correctly this $resource feature
Since $resource automatically converts the JSON string to object, you don't have to do call JSON.parse().
Just do
var Operator = $resource('http://127.0.0.1:8080\:8080/api/v1/operator/:operatorId', {
operatorId: '#id'
}, {
query: {
method: 'GET',
transformResponse: function (data) {
return data.meta.objects;
},
isArray: true
}
});
The json data you are sending is not an array, and the meta property is not something created by angular framework. If you are expecting that it gets deserialized into the objects array you have to return only that part and isArray would work.
For now what #sza mentions to get the array you override query and return data.meta.objects

Resources