Angular 8 ng
Nov 24 2020
Tôi có phù thủy API của League of Legends Champion trả lại những gì tôi nhận được từ Champion.service.
.ts đã cập nhật
@Component({ selector: 'app-champions', templateUrl: './champions.component.html', styleUrls: ['./champions.component.css'] })
export class ChampionsComponent implements OnInit {
public champions;
public arrayChampions;
constructor(private championsService:ChampionsService) { }
ngOnInit(): void {
this.getAllChampions(); }
getAllChampions(){
this.championsService.getChampions().subscribe(
data => { this.champions = data,
this.arrayChampions = Object.entries(this.champions.data).map(([k,v]) => ({ [k]:v })),
this.ArrayIterator();
},
err => {console.error(err)},
() => console.log("Champions cargados")
);
}
ArrayIterator() {
let IteratableArray = Array();
for (let item of Object.keys(this.arrayChampions[0])) {
var eventItem = Object.values(this.arrayChampions[0]);
IteratableArray.push(eventItem);
}
this.arrayChampions = IteratableArray[0];
}
}
Champion.service
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders} from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
}
@Injectable({ providedIn: 'root' }) export class ChampionsService {
constructor(private http: HttpClient) { }
getChampions(){
return this.http.get('http://ddragon.leagueoflegends.com/cdn/10.23.1/data/es_ES/champion.json');
}
HTML:
<div *ngFor="let arrayChampion of arrayChampions>
<a class="text-decoration-none">{{arrayChampion.id}}</a>
</div>
Thực tế là không có gì xuất hiện trong HTML. Tôi không biết rõ đâu là vấn đề.
Trả lời
1 SelakaNanayakkara Nov 24 2020 at 13:57
Phần tử đầu tiên của mảng của bạn là objectkể từ vì vì vậy bạn không thể lặp lại nó một cách thẳng thắn trong mẫu. Do đó, bạn cần phải biến đổi nó cho phù hợp để có thể lặp lại qua mẫu. Đối với điều đó, bạn có thể tiến hành như sau:
Từ đây với tôi đính kèm ví dụ stackblitz đang hoạt động ở đây
HTML mẫu:
<div *ngFor="let arrayChampion of arrayChampions>
<a class="text-decoration-none">{{arrayChampion.id}}</a>
</div>
Thành phần mẫu .ts:
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
name = "Angular 4";
arrayChampions: any;
data = [
{
Aatrox: {
id: "Aatrox",
key: "266"
},
Ahri: {
id: "Ahri",
key: "103"
},
Akali: {
id: "Akali",
key: "84"
}
}
];
constructor() {}
ngOnInit() {
this.ArrayIterator();
}
ArrayIterator() {
let IteratableArray = Array();
for (let item of Object.keys(this.data[0])) {
var eventItem = Object.values(this.data[0]);
IteratableArray.push(eventItem);
}
this.arrayChampions = IteratableArray[0];
}
}