我有来自api的json响应:
[
{
"id": 1,
"name": "Juan",
"edad": 20
},
{
"id": 2,
"nombre": "Pepe",
"edad": 26
},
...
]
我想用这个响应填充我的select2(使用lib ng-select2(,但显示nombre和edad,例如:Juan-20
我正确地收到了响应,但无法在select2中附加和显示它(我可以正确地重新生成这个库的示例,但这是硬编码的数据(。
这是我的尝试。在我的个人服务
getPersons(): Observable<Array<Select2OptionData>> {
return this.http.get<Array<Select2OptionData>>(this.API_URL);
}
人员组件
export class PersonsComponent implements OnInit {
public exampleData: Array<Select2OptionData>;
constructor(public personsService: PersonsService) {}
ngOnInit() { this.getPersons}
getPersons(): void {
this.personsService.getPersons().subscribe(
persons => {this.exampleData = persons;
console.log(persons);} // the information shows correctly in console.
)
}
persons.component.html
<ng-select2 [data]="exampleData"
[(ngModel)]="value">
</ng-select2>
结果:select2显示2个空行,但没有信息。我知道问题出在Select2OptionData接口上(它使用id、text(,但我是个新手,所以我如何解析或调整对Select2Option Data的响应?我应该在服务中还是在组件中执行它。ts??希望你能帮助我。
ng-select2的[data]
属性需要一个Select2Data
实例。
您的服务可能会返回一些与Select2根本无关的东西,比如Person[]
数组,在该数组中,您将Person
定义为具有以下属性的接口:
interface Person {
id: number;
name: string;
edad: number;
}
然后,在组件端,您可以使用rxjs的map
运算符,如下所示:
this.personsService.getPersons().pipe(
map((persons: Person[]) => persons.map((person: Person) => ({label: person.name, value: person.id})))
).subscribe((personsData: Select2Data) => {
this.exampleData = personsData;
});
并将组件的属性更改为正确的类型:
public exampleData: Select2Data;