我正在构建一个关于我所做的一些项目的角度应用程序。我有一个详细信息页面,显示项目的详细信息。
问题: 当我进入项目详细信息页面时,一切都是正确的。 但是当我切换项目变量(通过使用我在页面上的导航)时,依赖项组件不会更新,它们不会获得正确的项目ID。
包含所有组件的projectdetail.html页面:
<div class="container-content" *ngIf="project">
<div class="projectdetail">
<div class="thumbnail header">
<img [src]="project.img" [alt]="project.name" class="projectImage" />
<div>
<h2>{{project.name}}</h2>
<!--The programming component that you can see in the image-->
<programming-languages [ids]="project.languages"></programming-languages>
</div>
</div>
<div>
<carousel interval="5000" noWrap="false">
<slide *ngFor="let slidez of slides; let index=index">
<img [src]="slidez.image" class="carouselimg" />
<div class="carousel-caption">
<h4>Slide {{slidez.id}}</h4>
<p>{{slidez.text}}</p>
</div>
</slide>
</carousel>
</div>
<div class="thumbnail detail">
<p>{{project.description}}</p>
</div>
</div>
<div class="projects hidden-mm hidden-sm hidden-xs">
<projectsidelist [notShowId]="selectedProjectId"></projectsidelist>
</div>
</div>
语言组件代码:
import { Component, Input, OnInit } from '@angular/core';
import { ProgrammingLanguagesService } from '../services/programminglanguages.service';
import { ProgrammingLanguage } from '../models/programmingLanguage';
@Component({
selector: 'programming-languages',
templateUrl: 'app/components/programminglanguages.component.html',
providers: [ProgrammingLanguagesService]
})
export class ProgrammingLanguages implements OnInit {
@Input()
ids: number[];
programmingLanguages: ProgrammingLanguage[];
constructor(private programmingLanguagesService: ProgrammingLanguagesService) {
}
getProgrammingLanguages() {
this.programmingLanguagesService.getProgrammingLanguages().subscribe(programmingLanguages => {
var result: ProgrammingLanguage[] = [];
this.ids.forEach((key: number) => {
programmingLanguages.forEach((programmingLanguage: ProgrammingLanguage) => {
if (programmingLanguage.id == key)
{
result.push(programmingLanguage);
}
})
})
this.programmingLanguages = result;
});
}
ngOnInit() {
setTimeout(() => this.getProgrammingLanguages(), 0);
}
}
编程语言html:
<div class="languageoverlay">
<span *ngFor="let programmingLanguage of programmingLanguages; let lastElement = last">
<img [src]="programmingLanguage.img" [alt]="programmingLanguage.name" />
<span [hidden]="lastElement" class="languageseperator">+</span>
</span>
</div>
如果您需要额外的代码,请询问或参考github
的Github 运行github时的说明:转到http://localhost:3000/#/projectdetail/5
并单击左侧栏中的另一个项目。然后你看到了问题!
答案 0 :(得分:5)
您正确地将一组id传递给组件,但您从未听过所做的更改,因此可以快速修复:
在programminglanguages.component.ts中的更改此代码:
import { Component, Input, OnInit } from '@angular/core';
到
import { Component, Input, OnInit, OnChanges} from '@angular/core';
和
export class ProgrammingLanguages implements OnInit {
到
export class ProgrammingLanguages implements OnInit, OnChanges {
最后将此生命周期函数添加到您的类体:
ngOnChanges(): void {
this.getProgrammingLanguages();
}