将数组从一个组件传递到另一个组件的角度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数组从一个组件传递到另一个组件的角度相关的知识,希望对你有一定的参考价值。

[在我的Angular应用中,我试图将数组playlist从一个组件(1)传递到另一个(2)。最好的方法是什么。 @@ Input?

Component1.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';
import  faPlus  from '@fortawesome/free-solid-svg-icons';


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

  public data = [];
  public playlist = [];
  public apiData: any;
  public results = [];
  public loading = false;
  public noData: any;
  p: number = 1;
  faSearch = faSearch;
  faRedo = faRedo;
  faHeadphones = faHeadphones;
  faExternalLinkAlt = faExternalLinkAlt;
  faPlus = faPlus;

  searchQuery: string = "";
  clickMessage = '';

  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 = false;
      
    )
  

  closeAlert() 
    this.noData = false;
  

  addSongToPlaylist(itunes) 
    this.playlist.push(itunes);
    console.log('Playlist - ', this.playlist);


  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() 

  

Component2.ts

import  Component, OnInit, Input  from '@angular/core';
import  faHeadphones from '@fortawesome/free-solid-svg-icons';

@Component(
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
)
export class HeaderComponent implements OnInit 

  faHeadphones = faHeadphones;

  @Input()playlist = [];

  constructor()  

  ngOnInit() 
  


答案
播放列表的引用。如果您想传递播放列表的副本,请按照这种方式在

ContentComponent

playlistToPass = JSON.stringify(this.playlist); 然后转换回HeaderComponent中的数组
playlist = JSON.parse(this.playlistPassed);

以上是关于将数组从一个组件传递到另一个组件的角度的主要内容,如果未能解决你的问题,请参考以下文章

角度传递数组到另一个(非子)组件

以角度 8 将文本字段的值从一个组件传递到另一个组件

Reactjs - 将状态值从一个组件传递到另一个组件

在没有导航或路由的角度 2 类型脚本中,将数据一个组件传递到另一个组件的所有可能性是啥?

在 Angular 中,当组件不是父/子时,如何将值从一个组件传递到另一个组件?

将数组传递给组件