使用 jasonplaceholder 的 angular fake API,点击按钮后获取详细信息

问题描述

我正在使用 jsonplaceholder 开发一个虚拟 API,单击按钮后我会收到所有帖子,但我想在加载时获取用户 ID 和标题,单击标题后需要获取该 ID 的特定主体我如何实现这一点.

在 jasonplaceholder 中有 100 个带有 id、title、body 的帖子。在单击 getdata 时,我只需要 id 和 title 之后,当我单击标题时,我需要将正文作为段落或弹出窗口或其他内容

html

    <button (click)="get()">Get Data</button>
<div class="col-md mt-4 mb-4">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>id</th>
        <th>title</th>
        <th>body</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let d of data">
        <td><span>{{d.id}}</span></td>
        <td><span>{{d.title}}</span></td>
        <td><span>{{d.body}}</span></td>
      </tr>
    </tbody>
  </table>
</div>

ts

get(){
    this.userservice.getData().subscribe((data) =>{
    console.log(data)
    this.data = data
    })
  }

服务

getData():Observable<any>{
    const url = "https://jsonplaceholder.typicode.com/posts";
    return this.http.get(url)
   }

解决方法

一个简单的解决方案是使用 *ngIf 和一个变量,例如。 selectedId

<td (click)="showBody(d.id)"><span>{{d.title}}</span></td>
<td *ngIf="selectedId === d.id"><span>{{d.body}}</span></td>

然后在您的组件中启动它:

selectedId: any = null;

showBody(id: number){
   this.selectedId ? this.selectedId = null : this.selectedId = id;
}

这样当你再次点击标题时它会隐藏正文。

,

据我所知,您需要获取您单击的元素的 id 以显示元素的 body

所以要实现这一点,你可以这样写:

component.html

<tr *ngFor="let d of data" (click)="setBody(d)">
    <td><span>{{d.id}}</span></td>
    <td><span>{{d.title}}</span></td>
</tr>

<!-- Show selected item body here -->
<h1>Selected item body</h1>
<p>{{selectedItemBody}}</p>

component.ts 文件

[可选]:您可以在 ts 文件的顶部定义 POST 接口以获得更干净的代码:

interface POST {
  id: number;
  title: string;
  body: string;
}
  setBody(post: POST) {
    this.selectedItemBody = post.body;
    alert(this.selectedItemBody); // you can remove this alert
  }

我为您提供了this sample working code here in stackblits