3 回答
TA贡献1808条经验 获得超4个赞
根据您正在调用的 API
将您的 ts 更新为
getTasksFromService() {
let observable = this._httpService.getPokemon();
observable.subscribe((data) => {
this.tasks = data;
});
}
在你的网页中
<div>
<p>{{task.name}}</p>
</div>
您应该看到输出bulbasaur
当你有口袋妖怪列表时,你需要,但你发布的API(https://pokeapi.co/api/v2/pokemon/1/)包含上述代码工作的单个口袋妖怪fow的详细信息。*ngFor
TA贡献1873条经验 获得超9个赞
修改你的 getTasksFromService as
getTasksFromService() {
let observable = this._httpService.getPokemon();
observable.subscribe((data) => {
this.tasks = data["abilities"]; //because response data consist of array of ability in 'abilities'
console.log(data);
return data;
});
}
和你的 html 作为
<div *ngFor="let task of tasks; let idx = index">
<p>{{task.ability.name}}</p>
</div>
<router-outlet></router-outlet>
我希望这个解决方案适用于您的问题。
TA贡献1784条经验 获得超9个赞
请参阅更新的更改:
componen.ts :
import { Component, OnInit } from "@angular/core";
import { HttpService } from "./http.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent {
title = "pokemon";
tasks: any; // Make this as type of any
task = "";
constructor(private _httpService: HttpService) {}
ngOnInit() {
this.getTasksFromService();
}
getTasksFromService() {
this._httpService.getPokemon.subscribe(data => { // You can directly subscribe to this service, instead of creating an object and then subscribing to it.
this.tasks = data;
console.log(data);
});
}
}
服务:ts :
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root",
})
export class HttpService {
constructor(private _http: HttpClient) { }
getPokemon() {
return this._http.get("https://pokeapi.co/api/v2/pokemon/1/"); // You can directly return the observable.
}
}
由于API只返回一个信息,因此您不需要inhtml页面。*ngFor
网页 :
<p>{{task.name}}</p>
我希望这对你有用。
注意:我还提到了根据编码标准进行的变化。
添加回答
举报
