首页 文章

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

提问于
浏览
3

我已经从角度完成了tour of heroes . 它完美地运作 .

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

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

This is the code of the 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>

hero detail class

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());
     }      
}

The dashboard code

<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}">
    <div class="module hero">
      <h4>{{hero.name}}</h4>
    </div>
  </a>

The router is the same as the tutorial.

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'heroes', component: HeroesComponent },
  { path: 'detail/:id', component: HeroDetailComponent }
];

A bad solution:

经过研究,我发现有可能将(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

1 回答

  • 4

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

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

相关问题