简体   繁体   中英

In Angular2 routing, the URL changed but the content doesn't update

I am a beginner of Angular2. When I am learning angular2 routing service from https://angular.io/tutorial/toh-pt5 . I want to have herocomponent always displayed so I in the app.component.html like this:

<h1>{{title}}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
  <a routerLink="/dummy">Dummy</a>
</nav>
<app-heroes></app-heroes>
<router-outlet></router-outlet>
<app-messages></app-messages>

And here is the app-routing.module.ts:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard/dashboard.component';
import { HeroesComponent }      from './heroes/heroes.component';
import { HeroDetailComponent }  from './hero-detail/hero-detail.component';
import {DummyComponentComponent} from './dummy-component/dummy-component.component';
const routes: Routes = [
  { path: '', redirectTo: '/', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent },
  {path: 'dummy',component:DummyComponentComponent}
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

Strangely, when I click a hero on /dashboard or /heroes page it can direct to the correct URL and show the correct hero detail.

However, when I am on /detail/{{hero.id}} and click the hero on the hero component it can redirect the URL but the content in doesn't update. Can someone please help me with this?

if below is not issue then it should be issue that you are just changing parameter url that is reason its not updating

//put this code in your hero.component.ts file 
ngOnInit() {
this.route.params.subscribe((params) => {
   this.id = +params['id'];
   this.loadComponentAgain();
 });
}

above code monitor change in param value and update your component according to it.


There is issue because of this html

<app-heroes></app-heroes>
<router-outlet></router-outlet>

you are loading app-heroes component out side router-outlet , it should be loaded under router-outlet , so you should do this

<!-- <app-heroes></app-heroes> remove this-->
<router-outlet></router-outlet>

为了使用动态值更改路由,您需要像这样设置routerLink

[routerLink]="['/detail',hero.id]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM