3 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
根據(jù)您正在調(diào)用的 API
將您的 ts 更新為
getTasksFromService() {
let observable = this._httpService.getPokemon();
observable.subscribe((data) => {
this.tasks = data;
});
}
在你的網(wǎng)頁中
<div>
<p>{{task.name}}</p>
</div>
您應(yīng)該看到輸出bulbasaur
當(dāng)你有口袋妖怪列表時,你需要,但你發(fā)布的API(https://pokeapi.co/api/v2/pokemon/1/)包含上述代碼工作的單個口袋妖怪fow的詳細信息。*ngFor

TA貢獻1873條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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);
});
}
}
服務(wù):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
網(wǎng)頁 :
<p>{{task.name}}</p>
我希望這對你有用。
注意:我還提到了根據(jù)編碼標準進行的變化。
添加回答
舉報