首页 > 解决方案 > 如何在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>

标签: angulartypescript

解决方案


只需添加(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;
    })
}

推荐阅读