【发布时间】:2019-11-22 00:10:58
【问题描述】:
在我的 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() {
}
}
【问题讨论】:
-
组件通信的方法有很多种,主要的方法是输入(将数据传递给子节点)、输出(将数据传递给父节点)或共享服务(在任意组件之间传递数据)
-
你将如何使用输入方法传递数组,因为我看到这主要是使用字符串
标签: javascript angular