首页 > 解决方案 > 如何从组件角度获取数据并将其打印到 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;
  }
}

谢谢!

标签: javascripthtmlangular

解决方案


根据您调用的 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/)包含上述代码有效的单个口袋妖怪流的详细信息。


推荐阅读