I am attempting to create a 'simple' Ionic 2 / Angular 2 Application that provides information to voters from a Google CivicInfo API Call. Users submit their address and a Ionic2/Angular2 service provider takes the form params and creates a url query string. The response is put into an Observable.
CivicInfoProvider.ts
return this.http.get(this.BASE_URL, { search: params })
.toPromise()
.then(response => response.json() as UserData[], err => console.log(err));
With the response as a JSON Observable the user is taken to the Civic Info Listing page where the data is displayed for the user.
CivicInfoList.ts
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private info: CivicInfoProvider ) {
this.addr.street = this.navParams.get('street');
this.addr.city = this.navParams.get('city');
this.addr.state = 'PA';
this.addr.zip = this.navParams.get('zip');
this.searchString = this.addr.street + ' ' +
this.addr.city + ' ' +
this.addr.state + ' ' +
this.addr.zip;
this.userdata = this.info.getCivicInfo(this.searchString);
}
CivicInfoList.html
<ion-content padding>
<h6>Search Results For:</h6>
{{ (userdata | async)?.normalizedInput?.line1 }}
{{ (userdata | async)?.normalizedInput?.city }}
{{ (userdata | async)?.normalizedInput?.state }}
{{ (userdata | async)?.normalizedInput?.zip }}
<h6>Election Details:</h6>
<ion-list lines>
<ion-item>
Name: {{ (userdata | async)?.election?.name }}
</ion-item>
<ion-item>
Date: {{ (userdata | async)?.election?.electionDay }}
</ion-item>
</ion-list>
<h6>Your Polling Location:</h6>
<ion-item ngFor="location of userdata.pollingLocations">
{{ location }}
</ion-item>
<h6>Contests:</h6>
<ion-list lines>
<ion-item ngFor="contest of userdata.contests, [value]='object'">
{{ contest }}
</ion-item>
</ion-list>
</ion-content>
MY PROBLEM :: I CAN NOT figure out how to display the Objects that are stored in arrays pollingLocations from the JSON example below. I can display normalizedInput ...
In true Angular fashion there are no error messages or cryptic messages that do not lead to any help in documentation or Google searches.
Selectioned API Response
{
"kind": "civicinfo#voterInfoResponse",
"election": {
"id": "2000",
"name": "VIP Test Election",
"electionDay": "2017-06-06",
"ocdDivisionId": "ocd-division/country:us"
},
"normalizedInput": {
"line1": "911 Merrybell Lane",
"city": "Kennett Square",
"state": "PA",
"zip": "19348"
},
"pollingLocations": [
{
"address": {
"locationName": "KENNETT TOWNSHIP BLDG",
"line1": "801 BURROWS RUN RD",
"city": "CHADDS FORD",
"state": "PA",
"zip": ""
},
"notes": "",
"pollingHours": "",
"sources": [
{
"name": "Voting Information Project",
"official": true
}
]
}
],
Thanks for Your Help!
Screen Snap
Your json does not have an array of objects, you should use like this,
<ul>
<li *ng-for="#person of people.pollingLocations">
{{person.address | json}}}
</li>
</ul>
DEMO
Related
how can I get the information from this json to paint them in angular 10
{
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
for normal jsons I used this one, but that jeson has 2 arrays and it won't let me
return this.http.get<Country[]>("./assets/data.json");
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
<!-- html -->
<div *ngFor="let item of countri">
{{item.id}}
</div>
model
export interface Country {
id: number;
name: string;
}
and my subscribe
countri: Country[] = [];
this.countriesService.getCountries().subscribe(
countri => {
this.countri = countri;
console.log(countri);
},
err => console.log(err)
);
Use any.
1st way:
return this.http.get<any>("./assets/data.json");
2nd way define an proper interface for your data.
export interface IRequest {
countries: ICourtry[],
states: IState[]
}
export interface ICourtry{
id:number;
name: string;
}
export interface IState{
id:number;
name: string;
countryId: number;
}
return this.http.get<IRequest>("./assets/data.json");
This mentioned error(Error trying to diff '[object Object]') are because you are using this json somewhere in your template but it has no values. Hope it will fix it or provide the template code also.
Error trying to diff '[object Object]'. Only arrays and iterables are allowed , this error usually comes when you try to iterate through ngFor with an Object instead of an Array.
If you are using ngFor,
list.component.ts
data={
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
list.component.html
<ul>
<li *ngFor="let item of data.countries">
{{item.name}}
</li>
</ul>
or
<ul>
<li *ngFor="let item of data.states">
{{item.name}}
</li>
As the error suggests, you are most likely trying to iterate over an object rather than an array. Also, since the data you fetch is asynchronous you may make use of the following code to avoid any errors. It makes use of the async pipe along with the safe(?) operator.
.ts
jsonData;
ngOnInit() {
this.jsonData = this.http.get('./assets/data.json');
}
template
<div *ngFor="let country of (jsonData | async)?.countries">
{{ country | json}}
</div>
<div *ngFor="let state of (jsonData | async)?.states">
{{ state | json}}
</div>
When running the code below in my angular 1.x app I can see the first line returns the following :
[ { "id": 121, "valid": true }, { "id": 123431, "valid": false } ]
However when I try to display the valid or id property in the ng-repeat on the following line I see nothing whatsoever? What am i doing wrong??
{{ allItems | json }}
<div ng-repeat="item in allItems">
{{ item.valid }}
</div>
I have made a simple DRF page with the following output:
[
{
"id": 1,
"name": "Michel",
"city": "Florida",
"country": "United States"
},
{
"id": 2,
"name": "Hasan",
"city": "London",
"country": "United Kingdom"
}
]
I have the following code in HTML:
<script src="angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in info">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
I have the following in a .js file:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("localhost:8000/index/info/")
.success(function(response) {
$scope.info = response[array name was supposed to go here];
});
The tutorial that I am following is this, which has the whole data in a an array with an array name. They used the name after response, see the .js file code. My question is, how can I give a name to my array, or call this array without a name?
$scope.projects = [];
$http.get('/api/projects/').success(function(data) {
$scope.projects = data;
console.log($scope.projects);
});
Source:
Django and AngularJS - Sending query JSON data to Angular
I can't get my search field to filter my data from my .json file below.
As soon as i start typing in the search fields, all of the items disappear.
Here is my json file that works as my database.
[{
"id": 1,
"userId": 1,
"firstName": ["Jack", "text"],
"lastName": ["Rackum", "text"],
"phone": ["33221122", "tel"]
}, {
"id": 2,
"userId": 1,
"firstName": ["Ellery", "text"],
"lastName": ["Queen", "text"]
}, {
"id": 3,
"userId": 1,
"firstName": ["Minnie", "text"],
"lastName": ["Mouse", "text"]
}]
And here is my views file for the front-end
<div class="input">
<input type="text" placeholder="Søg" ng-model="query.$">
<i class="icon"></i>
</div>
<div class="item" ng-repeat="child in children | filter:query">
<img class="image" src="images/children/1.jpg">
<div class="content" >
<div class="header">
<a>
{{ child.firstName[0] }} {{ child.lastName[0] }}
</a>
</div>
</div>
</div>
And my controllers.js file
angular.module('ContactsApp')
.controller('ListController', function ($scope, Contact) {
$scope.children = Contact.query();
$scope.fields = ['firstName', 'lastName'];
$scope.firstname = ['firstName'];
$scope.lastname = ['lastName'];
$scope.phone = ['phone'];
});
And finally my factories file
angular.module('ContactsApp')
.factory('Contact', function ($resource) {
return $resource('/api/child/:id', { id: '#id' }, {
'update': { method: 'PUT' }
});
});
It looks like filters don't work well with searching within arrays. You might need to change your data structure.
Here's a Plunker:
http://plnkr.co/edit/pC0W6YwhTB9l0CUaZWy0?p=preview
Instead of using
{{child.firstName[0]}}
I used
{{child.firstName}}
with the appropriate changes in the data.
I have a controller where I declare the model like this:
$scope.Model =[];
after I make a rest call and the result I push it to the model:
$scope.Model.push(results.data);
The data returned can be in different length and size:
Name
Email
Items
Item 1
Item 2
Item n
Roles
Role 1
Role 2
Role n
What is the best practice of handling this with arrays in AngularJS and using ng-repeat in view in order to show the data?
Should I declare my array like this:
$scope.Model =[];
and push the results:
$scope.Model.push(results.data);
or like this:
$scope.Model =[{
Name: '',
Email: '',
Items: [{
Id: '',
Name: '',
Price: ''
}],
Roles: [{
Id: '',
Name: ''
}],
}];
and asign the results:
$scope.Model = results.data;
It is based on your response and scenarios. but ng-repeat expects Array or Array list.
1) Array
Example 1 (plain array response)
$scope.names= ["Apple", "Banana", "Orange"];
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
Example 2 (Object response that has array)
$scope.names= {
"fruits": ["Apple", "Banana", "Orange"]
};
<ul>
<li ng-repeat="x in names.fruits">
{{ x }}
</li>
</ul>
2) Array List
Example 1 (plain array list response)
$scope.names = [{
"id": "1",
"name": "Asik"
},
{
"id": "1",
"name": "John"
},
{
"id": "1",
"name": "Smith"
}];
<ul>
<li ng-repeat="x in names">
id:{{ x.id }}, name:{{ x.name }}
</li>
</ul>
Example 2 (Object response that has array list)
$scope.names = {
"success": "true",
"items": [{
"id": "1",
"name": "Asik"
},
{
"id": "1",
"name": "John"
},
{
"id": "1",
"name": "Smith"
}]
};
<ul>
<li ng-repeat="x in names.items">
id:{{ x.id }}, name:{{ x.name }}
</li>
</ul>
Basically, service/ajax response comes as Array or Array list. So you don't need to do the following steps.
$scope.Model =[];
$scope.Model.push(results.data);
But the above case comes in some situation (for eg: merging 2 service/ajax responses )
I have used the following:
angular.copy(results.data, $scope.Model)
This will actually copy the results from the rest servicve into my model without having to declare each property of the model.