将对象从 rest api 推送到数组 Angular

在我的 Angular 应用程序中,我调用了一个从 iTunes api 返回结果的 rest-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() {


  }

}


红糖糍粑
浏览 110回答 2
2回答

幕布斯6054654

如果在组件的 .ts 文件中,您的查询结果在变量中songs(这就是 this.data 的样子),在组件的 .html 中,您可以<ng-container *ngFor="let song of songs">&nbsp; &nbsp; <button type="button" (click)="addSongToPlaylist(song)">Add Song {{ song.name }}</button></ng-container>然后回到 .ts 文件addSongToPlaylist(song) {&nbsp; &nbsp; this.playlist.push(song);}

HUWWW

如果我错了,请纠正我,根据我的理解,您希望将来自 rest API 的查询结果添加到现有的歌曲数组中,即数据。您可以在这里使用扩展运算符的力量是示例。&nbsp; Search(){&nbsp; &nbsp; &nbsp; this.service.getAll(this.searchQuery).subscribe((results) => {&nbsp; &nbsp; &nbsp; this.loading = true;&nbsp; &nbsp; &nbsp; console.log('Data is received - Result - ', results);&nbsp; &nbsp; &nbsp; this.data = [...this.data,...results.results]; // spread operator&nbsp;&nbsp; &nbsp; &nbsp; this.loading = false;&nbsp; &nbsp; })&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript