我从角度上做了英雄之旅。它工作得很完美。
现在我想把仪表板组件放到英雄细节视图中。所以它给我展示了英雄的顶端,然后是英雄的细节视图。图像
我有一个路由器链接,它加载相同的组件,但是有不同的参数。我想知道,当我点击仪表板上的任何元素时,该怎么做才能加载不同的英雄。
--这是英雄的代码-细节.
<app-dashboard></app-dashboard>
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
</label>
<div><span>name: </span>{{hero.name}}</div>
</div>
<button (click)="goBack()">go back</button>
<button (click)="save()">save</button>
</div>英雄细节类
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
save(): void {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
}仪表板代码
<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>路由器与教程.相同
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'heroes', component: HeroesComponent },
{ path: 'detail/:id', component: HeroDetailComponent }
];--一个糟糕的解决方案:
经过一些研究,我发现了将(click)="reloadRoute()“添加到链接中的可能性,但这一次刷新了整个页面。
<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}" (click)="reloadRoute()">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>发布于 2017-12-14 17:03:49
与其使用快照,不如订阅params。这就是我的样子:
ngOnInit(): void {
this.route.params.subscribe(
params => {
const id = +params['id'];
this.getProduct(id);
}
);
}https://stackoverflow.com/questions/47808717
复制相似问题