在以下代码中,当我尝试访问全局变量时,它返回未定义的。如何更新变量,使其可用于其他功能?
episodes: EpisodeModel[] = [];
ngAfterViewInit(): void {
this.episodesService.getAllEpisodes().subscribe(data => {
this.episodes = data;
console.log(this.episodes); // shows array
this.showEpisodes(); // function to display episodes on the page - sets event listener ('click', this.showEpisodeInfo) - works
}
}
showEpisodeInfo(event) {
console.log(event); // works
console.log(this.episodes); // returns undefined
}
我忽略了一些细节,因为它太大了,无法发布:
showEpisodes(): void {
let episodes = this.episodes;
let document = this.shows.nativeElement.contentDocument;
let genres = Array.from(document.getElementsByClassName('genre')[0].getElementsByTagName('path'));
for (let i in episodes) {
let episode = <any>episodes.find((e: any) => {
return e.getAttribute('title') == episodes[i].genre;
});
let episodesGroup = document.getElementById('episodes');
if (episodes[i].episodeType.toLowerCase() === 'fantasy') {
let episode = document.createElementNS(svgNS, 'svg');
episode.setAttributeNS(null, 'style', 'overflow: visible;')
let episodeThumbnail = document.createElementNS(svgNS, 'circle');
episodeThumbnail.setAttributeNS(null, 'class', 'episode');
episodeThumbnail.setAttributeNS(null, 'fill', 'black');
episodeThumbnail.setAttributeNS(null, 'overflow', 'visible');
episodeThumbnail.addEventListener("click", this.showEpisodeInfo);
let episodeTitle = document.createElementNS(svgNS, 'title');
episodeTitle.innerHTML = episodes[i].episodeTitle;
episodeThumbnail.appendChild(episodeTitle);
episode.appendChild(episodeThumbnail);
episodesGroup.appendChild(episode);
}}}
答案 0 :(得分:1)
具体错误是由
引起的episodeThumbnail.addEventListener("click", this.showEpisodeInfo);
应该是
episodeThumbnail.addEventListener("click", event => this.showEpisodeInfo(event));
但是您的代码完全滥用了Angular。您不应该从组件执行DOM操作,也不添加事件侦听器。这就是模板的角色。
该组件应仅修改其状态,并且模板应使用指令(* ngIf,* ngFor等),属性绑定和事件绑定((click)="..."
)来显示状态。
阅读the documentation,因为您目前缺少Angular的全部知识。