2017-12-14 14 views
1

私はtour of heroesを角度から実行しました。それは完全に動作します。Angularの異なるパラメータで同じコンポーネントを更新する方法

ここで、ダッシュボードコンポーネントをヒーロー詳細ビューに配置します。それで、私は英雄のトップを示し、その後、英雄のディテールビューを示します。 Image

ルータのリンクには同じコンポーネントがロードされていますが、パラメータは異なります。私は、ダッシュボードから任意の要素をクリックすると、このヒーローに別のヒーローがロードされるように、何をすべきかを知りたいと思っています。

これはヒーロー-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> 
のコードであります

ルーターはチュートリアルと同じです。研究の後

私はすべての可能性は、リンクに(クリック)=「reloadRoute()」を追加することが、この1つはリフレッシュした少し:

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

悪いソリューションページ。

<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

答えて

0

代わりのスナップショットを使用して、のparamsに加入。私はこれをしようとしています

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

が、それは今の私には何も表示されません:これは私のように見えるものである 'ngOnInit():無効{ \t // constのID = + this.route.snapshot .paramMap.get( 'id'); \t \t // this.taskService.getTask(id) \t // .subscribe(タスク=> this.task =タスク); \t this.route.params.subscribe( \tのparams => { \t CONST ID = + paramsは[ 'ID']; \t this.taskService.getTask(ID); \t} \t)。 \t} ' – ValRob

+0

コンソールにエラーはありますか?サブスクリプションの中にconsole.logを追加すると、IDを取得していますか? – DeborahK

+0

私は、どのように知っているのか分かりませんが、this.route.params.subscribe(params => {const id = + this.route.snapshot.paramMap.get( 'id')this.heroService.getHero(id)。購読する(Hero => this.hero = hero);}); ' – ValRob

関連する問題