>im IOnic 2 和 Angular 中的新功能,我尝试过滤 Json 以仅显示特定值; 示例 仅按性别获取用户。 这是我的代码
首页.html
<ion-list>
<ion-item *ngFor="let item of items | filter: {item.gender:'female'}" (click)="itemClicked($event,item)">
<ion-avatar item-left>
<img src="{{item.picture.thumbnail}}">
</ion-avatar>
<h2>{{item.name.first | uppercase }}</h2>
<h3>{{item.name.last | uppercase }}</h2>
<p>{{item.gender}}</p>
<button ion-button item-right color="danger" (click)="buttonClick($event)">Button</button>
</ion-item>
</ion-list>
这是我使用 API 服务的 .ts 文件
import { Component } from '@angular/core';
import {Http} from '@angular/http';
import { NavController } from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public items:any;
constructor(public navCtrl: NavController,public http: Http) {
this.http = http;
this.http.get("http://api.randomuser.me/?results=10")
.subscribe(data =>{
//console.log(data['_body']);
this.items=JSON.parse(data['_body']).results;//Bind data to items object
},error=>{
console.log(error);// Error getting the data
} );
}
buttonClick(event){
console.log("button clicked");
console.log(event);
}
itemClicked(event,itemData){
console.log("item clicked");
console.log(event);
console.log(itemData);
}
}
但我的想法行不通有什么想法可以帮助我吗-??:`/
您可以在组件代码中执行此操作,而不是在视图中执行此操作...
import { Component } from '@angular/core';
import {Http} from '@angular/http';
import { NavController } from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public items: any;
constructor(public navCtrl: NavController, public http: Http) {
// this.http = http; <- You don't need this, this.http is already available because by declaring it in the constructor, now a public property is created in the component
this.http.get("http://api.randomuser.me/?results=10")
.map(data => data.json().results) // Instead of getting the _body manually, you can use the map method from RxJS
.subscribe(data =>{
//console.log(data);
this.items = data.filter(item => item.gender === 'female');
},error=>{
console.log(error);// Error getting the data
});
}
// ...
}
现在在您看来
<ion-list>
<ion-item *ngFor="let item of items" (click)="itemClicked($event,item)">
<ion-avatar item-left>
<img src="{{ item.picture.thumbnail }}">
</ion-avatar>
<h2>{{ item.name.first | uppercase }}</h2>
<h3>{{ item.name.last | uppercase }}</h2>
<p>{{ item.gender }}</p>
<button ion-button item-right color="danger" (click)="buttonClick($event)">Button</button>
</ion-item>
</ion-list>