过滤具有多个对象数组的响应,返回 Observable



我正在尝试过滤具有不同属性的 Angular 7 中的对象数组,并且我试图使一个假的可观察(来自我的服务的 JSON 响应(并尝试映射到我的 HTML。

我不知道如何过滤具有多个属性的对象数组。

这是我可观察的控制台结果。

[Object, Object, Object]
0: Object
cities: Array[1]
id: 1
name: "France"
places: Array[1]
0: Object
place1: "effil tower"
place2: "new discover"
__proto__: Object
texts: Array[1]
0: "a"
__proto__: Object
1: Object
cities: Array[1]
id: 2
name: "Germany"
places: Array[1]
0: Object
place1: ""
__proto__: Object
texts: Array[1]
0: "a"
__proto__: Object
2: Object
cities: Array[3]
0: "Roma"
1: "Milan"
2: "Napoli"
id: 3
name: "Italy"
__proto__: Object

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular 5';
selectedCountry: any;
cities = {};
places = {};
texts = {};
countries = [{
'id': 1,
'name': 'France', 
'cities': ['Paris'],
'places': [{ 
'place1':'effil tower',
'place2':'new discover'
}],
'texts': ['a']
},
{
'id': 2, 
'name': 'Germany',
'cities': ['Hamburg'],
'places': [{ 
'place1':''
}],
'texts': ['a']
},
{
'id': 3, 
'name': 'Italy',
'cities': ['Roma', 'Milan', 'Napoli']
},
];
ngOnInit() {
}
onChange(deviceValue) {
console.log(deviceValue);
this.getValues(deviceValue).subscribe( data =>{
console.log(data);
this.cities = data.filter(x => x.id == deviceValue)[0].cities;
}
// this.places = this.countries.filter(x=> x.id == val)[0].places;
// this.texts = this.countries.filter(x=> x.id == val)[0].texts;
// console.log(this.cities);
);
}
getValues(val){
return Observable.of(this.countries);
console.log(this.countries);

}
}
p {
font-family: Lato;
}
<hello name="{{ name }}"></hello>
<select name="city" class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
<option *ngFor="let country of countries"  [value]="country.id">{{country.name}}</option>
</select>
<div style=" padding-top: 0.5em; " >
<select id="sel1" name="Country" class="">
<option *ngFor="let city of cities" [value]="city">{{city}}</option>  
</select>
</div>

<div style=" padding-top: 1em; ">
<label *ngFor="let place of places">
<input type="radio" name="options">{{place}}
</label>
</div>
<!-- <div style=" padding-top: 0.5em; " > 
<label *ngFor="let in of texts">{{in}} :
<input type="text">
</label>
</div> -->
<div style=" padding-top: 1em; ">
<label *ngFor="let place of texts">{{place}} : 
<input type="text" >
</label>
</div>

只需将属性初始化为数组而不是对象即可。代码是

cities = [];
places = [];
texts = [];

我在上面做了一个堆栈闪电战,它有很多控制台错误。不确定它会持续多久,但这是链接: https://stackblitz.com/edit/angular-yxwpaa

最新更新