将对象从Rest API推入Angular数组

时间:2019-11-21 15:06:49

标签: javascript angular

在我的Angular应用程序中,我正在调用rest-api,它将带回iTunes API的结果。我想做的是,能够有一个添加按钮,使我可以将对象(歌曲对象)添加到数组中,以便用户可以创建自己的播放列表。我如何将对象从其余API推入数组?到目前为止,我对Component.ts的代码是:

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../services/api.service';
import { FormGroup, FormControl } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { faRedo } from '@fortawesome/free-solid-svg-icons';
import { faHeadphones} from '@fortawesome/free-solid-svg-icons';
import { faExternalLinkAlt} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss']
})
export class ContentComponent {

  public data = [];
  public apiData: any;
  public loading = false;
  public noData = false;
  p: number = 1;
  faSearch = faSearch;
  faRedo = faRedo;
  faHeadphones = faHeadphones;
  faExternalLinkAlt = faExternalLinkAlt;
  searchQuery : string = "";

  constructor(private service: ApiService) { }

  getAll() {
    this.service.getAll(this.searchQuery).subscribe((results) => {
      this.loading = true;
      console.log('Data is received - Result - ', results);
      this.data = results.results;
      this.loading = false;

      if (this.data.length <= 0) {
        this.noData = true;
      } else if (this.data.length >= 1) {
        this.noData = false;
      } else {
        this.noData = true;
      }
    })
  }

  refresh(): void {
    window.location.reload();
  }  

  Search(){
   this.service.getAll(this.searchQuery).subscribe((results) => {
      this.loading = true;
      console.log('Data is received - Result - ', results);
      this.data = results.results;
      this.loading = false;
    })
  }
  ngOnInit() {

  }
}

2 个答案:

答案 0 :(得分:1)

如果在组件的.ts文件中,查询结果存储在变量songs中(这是this.data的样子),则在组件的.html中,您可以

<ng-container *ngFor="let song of songs">
    <button type="button" (click)="addSongToPlaylist(song)">Add Song {{ song.name }}</button>
</ng-container>

然后返回.ts文件

addSongToPlaylist(song) {
    this.playlist.push(song);
}

答案 1 :(得分:0)

如果我错了,请纠正我,根据我的理解,您想将来自其余API的查询结果添加到现有的歌曲数组(即数据)中。您可以在此处使用扩展算子的功能。

  Search(){
      this.service.getAll(this.searchQuery).subscribe((results) => {
      this.loading = true;
      console.log('Data is received - Result - ', results);
      this.data = [...this.data,...results.results]; // spread operator 
      this.loading = false;
    })
  }