gpt4 book ai didi

angular - 如何在 Angular 中使用不同的参数更新相同的组件

转载 作者:太空狗 更新时间:2023-10-29 18:19:20 25 4
gpt4 key购买 nike

我已经完成了 tour of heroes从 Angular 。它工作得很好。

现在我想将仪表板组件放在英雄详细信息 View 中。所以它向我展示了英雄的顶部,然后是英雄细节 View 。 Image

我有一个路由器链接,它加载相同的组件,但具有不同的参数。我想知道该怎么做才能在我单击仪表板中的任何元素时加载不同的英雄。

这是 hero-detail.component.html 的代码

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

Github

最佳答案

不使用快照,而是订阅参数。这是我的样子:

ngOnInit(): void {
this.route.params.subscribe(
params => {
const id = +params['id'];
this.getProduct(id);
}
);
}

关于angular - 如何在 Angular 中使用不同的参数更新相同的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47808717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com