javascript - Angular2路由中,URL改变了但内容没有更新

标签 javascript angular angular2-routing

我是 Angular2 的初学者。当我从https://angular.io/tutorial/toh-pt5学习Angular2路由服务时。我想让 HeroComponent 始终显示,所以我在 app.component.html 中像这样:

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

这是 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 {}

奇怪的是,当我点击 /dashboard/heroes 页面上的英雄时,它可以定向到正确的 URL 并显示正确的英雄详细信息。

但是,当我在 /detail/{{hero.id}} 上并单击英雄组件上的英雄时,它可以重定向 URL,但其中的内容不会更新。有人可以帮我解决这个问题吗?

最佳答案

如果下面不是问题,那么问题应该是您只是更改了参数 url,这就是它不更新的原因

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

上面的代码监视参数值的变化并根据它更新您的组件。


由于此 html 而出现问题

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

您正在 router-outlet 外部加载 app-heroes 组件,它应该加载到 router-outlet 下,所以您应该这样做这个

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

关于javascript - Angular2路由中,URL改变了但内容没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480374/

相关文章:

javascript - 从对象的子数组中删除数组的每个元素?

css - 当我向按钮添加自定义 Angular 类时,为什么 Angular Material 设计会消失?

angular - 如何在angular2中使用子域进行路由?

angular - 模板解析错误 : Can't bind to 'ngbTypeahead' since it isn't a known property of 'input

c# - 添加 Azure AD 身份验证时出现 CORS 错误

angular - 具有相同父布局 Angular 功能模块路由

Angular 2 : Where is url 'api/heroes' defined?

javascript - Angular 双向数据绑定(bind)和监视父组件的变化

javascript - PhoneGap本地存储sql删除语句

javascript - 为 IE8 添加动态 'filter' CSS 属性未正确分配