问题描述
我从控制台日志中获得了所需的值列表,但是我不知道如何在视图中输出它。有人可以帮我吗。
这是我的打字稿文件:
customFunction(val: any) {
this.modifiedText = val + " was selected from the dropdown";
let id = val;
this.pokeService.getGenerationSpecies(id).subscribe((details) => {
this.species = Object.values(details);
this.pokemonSpecies = Object.values(this.species[6]);
let iterator = this.pokemonSpecies.values();
for (let elements of iterator) {
console.log("result:",elements.name);
}
});
}
<ion-item>
<ion-label [(ngModel)]="customFunction"><b>{{elements.name}}</b></ion-label
>
</ion-item>
编辑:
这是我的服务供您参考:
getGenerationSpecies(index) {
return this.http.get(`${this.baseUrl}/generation/${index}?limit=25`).pipe(
map((species) => {
let pokemonSpecies = Object.keys(species);
species["id"] = pokemonSpecies.filter((id) => id);
console.log("species:",species);
return species;
})
);
}
有人可以告诉我正确的方法吗?非常感谢!
解决方法
由于您提到的是列表,因此您需要使用*ngFor
来遍历列表elements.name
中的每个项目。在这种情况下,现在发生的事情是您获得了整个列表并尝试一次打印它。
可能看起来像这样(尚未测试):
<ion-item *ngFor='let name of elements.names'>
<ion-label .... >{{ name }}</ion-label>
</ion-item>
,
尝试以下操作:
<ion-item *ngFor="let element of pokemonSpecies.values()">
<!-- depending on what you went to send to your customFunction,change the parameter -->
<ion-label [(ngModel)]="customFunction(element)"><b>{{element.name}}</b></ion-label
>
</ion-item>
,
在your.component.ts
中:
export class YourComponent implements OnInit {
elements: any;
constructor(
) { }
ngOnInit(): void {
}
customFunction(val: any) {
this.modifiedText = val + " was selected from the dropdown";
let id = val;
this.pokeService.getGenerationSpecies(id).subscribe((details) => {
this.species = Object.values(details);
this.pokemonSpecies = Object.values(this.species[6]);
this.elements = this.pokemonSpecies.values();
});
}
}
在您的your.component.html
中:
<div *ngFor="let item of elements,let i=index">
<ion-item>
<ion-label><b>{{item.name}}</b></ion-label
>
</ion-item>
</div>
在your.service.ts
中添加返回类型Observable<any>
:
getGenerationSpecies(index): Observable<any> {
return this.http.get(`${this.baseUrl}/generation/${index}?limit=25`).pipe(
map((species) => {
let pokemonSpecies = Object.keys(species);
species["id"] = pokemonSpecies.filter((id) => id);
console.log("species:",species);
return species;
})
);
}