Unable to access properties of JSON code through angularJS service - json

I am trying to access properties of the following JSON structure through AngularJS factory and service methods:
{
"#context": {
"firstname": "http://xmlns.com/foaf/0.1/firstname",
"lastname": "http://xmlns.com/foaf/0.1/lastname"
},
"members":[
{
"firstname":"Debjit",
"lastname":"Kumar"
},
{
"firstname":"Hari",
"lastname":"Haran"
},
{
"firstname":"Kaushik",
"lastname":"Shrestha"
}
]
}
But I am not able retrieve properties of the retrieved JSON object.
The following is my angularJS code:
angular.module('rdfa',['ngResource']).config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {controller: RdfaCtrl});
}])
.factory('members', function($resource){
return $resource('Json.json', {}, { query: {method:'GET', isArray:false} } );
})
.service('jsonservice',function(members){
this.members=members.query();
});
function RdfaCtrl($scope,jsonservice){
$scope.members=jsonservice.members.members;
console.log(jsonservice.members); // outputs correct JSON structure
console.log(jsonservice.members.members); // outputs undefined
console.log(jsonservice.members['#context']); // outputs undefined
}

You are making an asynchronous HTTP request, you cannot just simply print the output on the same call cycle. In order to do that you need to add a success callback handler in the query action, for example:
members.query(function(value) {
console.log(value); // Resource object
console.log(value.members); // members object
console.log(value['#context']); // #context object
});
Check this plunker for a working example: http://plnkr.co/edit/TFlQ6cDkIA3rpjkvHtOA?p=preview

Related

Angular 2: Access object data

In my Angular RC2 app I make an observable HTTP call that returns the following JSON to me from the API:
{
"success":true,
"data":
{
"Type": 1
"Details":{
"Id":"123",
"Name":"test",
"Description":"test"
}
}
}
I map the data like this:
this._myService.get(id)
.subscribe(
(data) => {
this.details = data.Details;
this.type = data.Type;
},
(error) => {
this.setError(error);
}
);
How do I access the values inside the "Details" object from here?
I tried:
{{details.Name}}
But that won't work and I can't use ngFor to loop it either.
You could use the Elvis operator for this:
{{details?.Name}}
As a matter of fact, you load your data asynchronously so details is undefined at the beginning.

How to have a custom value in JSON with JQueryi UI Autocomplete?

I'm using the JQuery UI autocomplete plugin (cached version) with JQuery-UI 1.11.1
Due to some server-side changes in the JSON I am using as source, I need to adapt my code.
Here is an example of my JSON:
[{
"name": "Varedo"
}, {
"name": "Varena"
}, {
"name": "Varenna"
}, {
"name": "Varese"
}]
produced by an URL with this style:
[url]/?name=vare
Since the GET variable is different from the default one ("term"), I already adapted my code for the custom request as suggested here:
$(function () {
var cache = {};
$("#searchTextField").autocomplete({
minLength: 3,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("[url]", {
name: request.term
}, function (data, status, xhr) {
cache[term] = data;
response(data);
});
}
});
});
However I need to also adapt the code in order to use a custom JSON value (the default is "value" http://api.jqueryui.com/autocomplete/#option-source) which is in my case is "name" (as you can see from the JSON).
How can I do that?
At the moment this is what I get from the autocomplete:
So I guess I am somehow giving as response JS Objects and not strings.
Thanks in advance.
Currently you're saving the response as it is into your cache object, which is not valid format for jQuery UI autocomplete. You should convert the data into proper format digestable for autocomplete.
Either you should pass an array of strings, or an array of objects having label and value properties.
Since the response only contains name properties, you can convert it into an array of strings using jQuery map() method and save it in cache variable as follows:
$("#searchTextField").autocomplete({
minLength: 3,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("[url]", {
name: request.term
}, function (data, status, xhr) {
cache[term] = $.map(data, function (obj) { // returns array of strings
return obj.name
});
// return the new array rather than original response
response(cache[term]);
});
}
});

AngularJS - How to data bind an object within a JSON object

Using the included http post, I should get back the JSON object below. I want to take the LeagueDictionary data in the JSON below and create an object so I can use it in a for each loop on my client, but I can't wrap my head around how to structure that code in the http call.
{
"Id": 0,
"UserName": null,
"NickName": null,
"Email": "email#company.com",
"Password": null,
"Admin": false,
"Validated": false,
"Key": "oOE0QbOhjK17pNeKDPEFti5On27R3b",
"LeagueDictionary": {
"1": "League #1",
"2": "League #2"
}
}
using this call:
$scope.getLeagues = function() {
$http({
method: 'POST',
url: 'http://xxxxxxxxxxxxxxxxxx',
data: ???,
})
}
If someone give me a nudge on how to data bind that particular part of the JSON, I'd appreciate the help. I'm not sure how to strip the LeagueDictionary section out and make an object out of it.
You could set up a service that gets your data, so you can get $http and such out of your controller. Say...
app.factory('DataService', function ($http) {
return {
get: function () {
return $http.get('data.json'); // post & url goes here
}
};
});
In your controller, use then to access the response data after promise has been resolved (catch() and finally() are available, too).
app.controller('MainCtrl', function ($scope, DataService) {
DataService.get().then(function (response) {
$scope.leagueDictionary = response.data.LeagueDictionary;
});
});
Related HTML template would be
<body ng-controller="MainCtrl">
<div ng-show="leagueDictionary">
<span ng-repeat="(key,val) in leagueDictionary">
{{ val }} <br>
</span>
</div>
</body>
Using your data this gives you
See example plunker here http://plnkr.co/edit/j6bmmQ
You can just access the LeagueDictionary property of the response, and then iterate over that in ng-repeat. Obviously I don't know exactly what your scopes look like, but this should get you started:
//JS
$http.post('/someUrl', { 'foo': 'bar' }).success(function(data) {
myController.myModel.leagueDictionary = data.LeagueDictionary;
});
//HTML
<tr ng-repeat="(leagueNum, leagueName) in leagueDictionary">

Displaying json data in angularjs

I would like to display data returned from service call into view:
Service Code :
.service('HomeExchangeList', function ($rootScope, $http, $log) {
this.getHomeExchange = function() {
var rates = $http({
method: 'GET',
url: 'http://localhost:8080/feeds/homerates_android.php'
}).success(function (data) {
$log.log(data);
return data;
});
return homeRates;
};
})
JSON Data returned by service
{
"record":[
{
"Name":"GBP\/USD",
"Ticker":"GBP\/USD",
"Price":"0.5828",
"Open":"0.5835",
"High":"0.5848",
"Low":"0.5828",
"PercentagePriceChange":"0.1371",
"Movement":"0.0800",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"EUR\/USD",
"Ticker":"EUR\/USD",
"Price":"0.7330",
"Open":"0.7344",
"High":"0.7351",
"Low":"0.7327",
"PercentagePriceChange":"0.2585",
"Movement":"0.1900",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"GHS\/USD",
"Ticker":"GHS\/USD",
"Price":"3.3350",
"Open":"3.2650",
"High":"3.3500",
"Low":"3.2650",
"PercentagePriceChange":"0.8915",
"Movement":"3.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"KES\/USD",
"Ticker":"KES\/USD",
"Price":"87.7000",
"Open":"86.2970",
"High":"87.6500",
"Low":"86.1800",
"PercentagePriceChange":"0.0661",
"Movement":"5.8000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"MUR\/USD",
"Ticker":"MUR\/USD",
"Price":"30.2925",
"Open":"29.1460",
"High":"29.4300",
"Low":"29.0500",
"PercentagePriceChange":"-0.0909",
"Movement":"-2.7500",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"MWK\/USD",
"Ticker":"MWK\/USD",
"Price":"393.5000",
"Open":"393.3900",
"High":"393.3900",
"Low":"385.0000",
"PercentagePriceChange":"-0.2548",
"Movement":"-100.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"NGN\/USD",
"Ticker":"NGN\/USD",
"Price":"162.3000",
"Open":"160.0600",
"High":"162.4000",
"Low":"160.0600",
"PercentagePriceChange":"0.2459",
"Movement":"40.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"ZAR\/USD",
"Ticker":"ZAR\/USD",
"Price":"10.6659",
"Open":"10.6751",
"High":"10.7162",
"Low":"10.6523",
"PercentagePriceChange":"0.9840",
"Movement":"10.6000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"ZMK\/USD",
"Ticker":"ZMK\/USD",
"Price":"47.7014",
"Open":"47.3850",
"High":"47.7000",
"Low":"46.8900",
"PercentagePriceChange":"0.0067",
"Movement":"0.3165",
"DateStamp":"2013\/07\/27",
"TimeStamp":"01:55:00"
}
]
}
Controller code
function HomeCtrl($scope, Page, $location, HomeExchangeList) {
$scope.rates = HomeExchangeList.getHomeExchange();
$scope.$on('HomeExchangeList', function (event, data) {
$scope.exchangeRates = data;
});
}
View
<ul id="home-rates" ng-repeat="rate in exchangeRates">
<li><span class='rate-symbol'>{{rate.Name}}</span><span class='rate-amount'>{{rate.Price}}</span></li>
</ul>
I would like to display the data returned by in the service in the view but it doesn't seem to be working. Please help
First, $http invocations all return a promise, not the result of your request. Your service should just return the result of the $http call, and your controller needs to attach a .success handler to receive the data and set it on the scope of your controller.
.service('HomeExchangeList', function ($rootScope, $http, $log) {
this.getHomeExchange = function() {
var rates = $http({
method: 'GET',
url: 'http://localhost:8080/feeds/homerates_android.php'
}).success(function (data) {
$log.log(data);
// removed your return data; it doesn't do anything, and this success is only added to log the result. if you don't need the log other than for debugging, get rid of this success handler too.
});
return rates;
};
})
function HomeCtrl($scope, Page, $location, HomeExchangeList) {
HomeExchangeList.getHomeExchange().success(function(data) {
$scope.exchangeRates = data;
});
}
Second, the root of your JSON is not an array, so you can't enumerate through just exchangeRates alone. Perhaps you meant exchangeRates.record.
try to assign data.record to $scope.exchangeRates instead of data... as data doesnt hold the array of records... it holds record which then holds the array
First of all, your service function always returns undefined:
var rates = ...,
return homeRates;
It should be
return rates;
Second, once that is fixed, the service doesn't return data. It returns a promise, and you can't iterate on a promise. What you need in the controller is:
HomeExchangeList.getHomeExchange().then(function(data) {
$scope.rates = data.record;
}
The call to $scope.$on doesn't make any sense. $scope.$on is used to listen for events. Not to get data from a promise.
And finally, your view must iterate over these retes, and not over exchangeRates:
ng-repeat="rate in rates">

AngularJS ngResource Send data to server with JSON and get response

In my angular JS app i need to send data to server:
"profile":"OLTP",
"security":"rsh",
"availability":"4",
"performance": {
"TRANSACTION_PER_SEC":1000,
"RESPONSE_TIME":200,
"CONCURRENT_CONNECTION_COUNT":500,
"STORAGE_SIZE":200,
"TOTAL_CONNECTION_COUNT":500
}
and in return i'll get
{"estimate" : 1600,"quoteid" : "Q1234"}
I was trying to do that with $resource but I am lost in syntax.
app.factory("VaaniEstimateService", function($resource) {
var requestURL = "http://128.34.32.34:8080/enquiry";
return $resource(requestURL, {callback: 'JSON_CALLBACK'}, { get: { method:'JSON'}, isArray:false });
});
Can you please provide me something to get me on the right path.
You must use JSONP method and insert JSON_CALLBACK keyword to your url as callback function.
app.factory("VaaniEstimateService", function($resource) {
return $resource("http://128.34.32.34:8080/enquiry?callback=JSON_CALLBACK", {}, {
get: {
method:'JSONP'
},
isArray:false
}).get({
profile:"OLTP",
security:"rsh",
availability:"4",
"performance.TRANSACTION_PER_SEC":1000,
"performance.RESPONSE_TIME":200,
"performance.CONCURRENT_CONNECTION_COUNT":500,
"performance.STORAGE_SIZE":200,
"performance.TOTAL_CONNECTION_COUNT":500
}, function (response) {
console.log('Success, data received!', response);
});
});
Your params will be sent as query params. Angularjs will automatically generate a global function for callback and replace its name with JSON_CALLBACK keyword. Your server must return json as javascript code by calling function that sent with callback parameter. For example, AngularJS is going to make GET request to that url:
http://128.34.32.34:8080/enquiry?callback=angular.callbacks._0?availability=4&performance.CONCURRENT_CONNECTION_COUNT=500&performance.RESPONSE_TIME=200&performance.STORAGE_SIZE=200&performance.TOTAL_CONNECTION_COUNT=500&performance.TRANSACTION_PER_SEC=1000&profile=OLTP&security=rsh
And your server must return response like that:
angular.callbacks._0({"estimate" : 1600,"quoteid" : "Q1234"});
Hope that's enough to give you an idea how jsonp works.