javascript - 如何从组件角度获取数据并将其打印到 html 中?
问题描述
如何从组件角度获取数据并将其打印到 html 中?我正在尝试从我的组件中获取我的 html 中的口袋妖怪名称
这是我的 app.components.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 = [];
task = "";
constructor(private _httpService: HttpService) {}
ngOnInit() {
this.getTasksFromService();
}
getTasksFromService() {
let observable = this._httpService.getPokemon();
observable.subscribe((data) => {
this.tasks = data["data"];
console.log(data);
return data;
});
}
}
这是我的 HTML:
<div *ngFor="let task of tasks; let idx = index">
<p>{{task.name}}</p>
</div>
<router-outlet></router-outlet>
这是我的 http.service.ts:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root",
})
export class HttpService {
constructor(private _http: HttpClient) {
this.getPokemon();
}
getPokemon() {
let pokemon = this._http.get("https://pokeapi.co/api/v2/pokemon/1/");
return pokemon;
}
}
谢谢!
解决方案
根据您调用的 API
将您的 ts 更新为
getTasksFromService() {
let observable = this._httpService.getPokemon();
observable.subscribe((data) => {
this.tasks = data;
});
}
在你的 html
<div>
<p>{{task.name}}</p>
</div>
你应该看到bulbasaur
输出
当您有口袋妖怪列表时,您需要*ngFor
,但您发布的 API(https://pokeapi.co/api/v2/pokemon/1/)包含上述代码有效的单个口袋妖怪流的详细信息。
推荐阅读
- reactjs - React.JS:嵌套过滤器/映射数组
- python - NLTK wordnet 不包含词汇术语 - Python
- qt - 无法初始化 GLX -- 虚拟机上的 CLI
- wordpress - 使用页面访问令牌从客户端进行 Facebook Graph API 调用是否安全?
- python - 如何将 csv 文件添加到 Django 模型中
- cmake - CMake 导出包未按预期工作
- python - bigquery,extract_table AttributeError:“客户端”对象没有属性“数据集”
- javascript - 视频滑块停止的js代码
- c# - 反序列化服务器返回字符串到 JSON
- c# - Farseer (Box2D) - 通过使用双精度或小数而不是浮点数来增加最大世界大小?