angular - 如何在Angular中单击按钮时调用rest api
问题描述
我有一个角度应用程序,目前它有一些来自休息 api 的数据。我只想在单击功能上调用该 api,实现此功能的正确方法是什么?
组件.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../services/api.service';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.scss']
})
export class ContentComponent implements OnInit {
public data = [];
public apiData: any;
constructor(private service: ApiService) { }
private getAll() {
this.service.getAll().subscribe((results) => {
console.log('Data is received - Result - ', results);
this.data = results.results;
})
}
ngOnInit() {
//this.getAll();
}
onClick() {
this.getAll()
}
}
html
<div class="jumbotron hero">
<div class="container">
<h1 class="display-4 text-center header mb-5">SEARCH</h1>
<form>
<div class="row">
<div class="col-8">
<div class="form-group">
<label for="inputPassword2" class="sr-only">Search</label>
<input type="password" class="form-control form-control-lg" id="inputPassword2"
placeholder="Search iTunes...">
</div>
</div>
<div class="col-4">
<button (click)="onClick" class="btn btn-primary btn-block btn-lg">Get All</button>
</div>
</div>
</form>
</div>
</div>
<div class="container" >
<table class="table">
<thead class="thead-light">
<tr>
<th>Artwork</th>
<th>Artist</th>
<th>Title</th>
<th>Genre</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of data">
<td><img src="{{user.artworkUrl60}}"></td>
<td>{{user.artistName}}</td>
<td>{{user.collectionName}}</td>
<td>{{user.primaryGenreName}}</td>
<td>{{user.collectionPrice}}</td>
</tr>
</tbody>
</table>
</div>
解决方案
只需添加(click)
事件处理程序并调用getAll()
<button (click)="getAll()" class="btn btn-primary btn-block btn-lg">Get All</button>
删除函数调用ngOnInit()
在 component.ts
getAll() {
this.service.getAll().subscribe((results) => {
console.log('Data is received - Result - ', results);
this.data = results.results;
})
}
推荐阅读
- javascript - 转换 GM_addstyle 添加没有 GM 的样式
- python - 来自非方阵的非对角线元素
- ios - Unity FIrebase 使用 Apple 登录
- angular - Angular 快速刷新从本地存储加载的项目
- python - 使用 Bazel 为 aarch64 交叉编译 tensorflow-addons
- sql - ROW_NUMBER Oracle - 奇怪的行为(添加行)
- java - 用户存储 SPI 中的 Keycloak 自定义异常
- c - 成对短字符串段比较问题的快速实现
- javascript - 如何随机使地图中的图像一张一张地出现淡入淡出?
- c++ - 显示 C++ 格式的日期