gpt4 book ai didi

Angular 组件在路线更改时不会重新加载

转载 作者:行者123 更新时间:2023-12-02 20:32:24 25 4
gpt4 key购买 nike

我正在学习 Angular,在我的项目中,我创建的导航栏提供了 routerLink 用于导航到页面。

    <ul>
<li> <a href="#">Home</a></li>
<li> <a href="#" [routerLink]="['/about']" >about us</a></li>
<li> <a href="#" [routerLink]="['/contact']" >contact us</a></li>
</ul>

这是我的 app.module.ts ,我在其中设置了用于导航的路由器。

 imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([
{ path:"**", component: HomeComponent,pathMatch: 'full' },
{ path:"about", component: AboutComponent },
{ path:"contact" , component: ContactComponent }
])
],

所以,当我运行它时,它运行得很好,它首先进入主页,但是当我单击“关于我们”页面时,查询字符串路由器中的联系页面将发生变化,但内容不会改变,主页的内容与其相同是的,这是我的主页和关于我们的页面。这是 m home.component.ts

constructor(private _avRoute: ActivatedRoute,
private _cmsService: CmsService,
private _router: Router) { }

ngOnInit() {
this.getConsultHome();
}

getConsultHome(){
this._cmsService.getcmsConsultHome()
._router.params.subscribe(data =>{ this.data = data }
, error => this.errorMessage = error);
}

这是我的about.component.ts

  constructor(private _avRoute: ActivatedRoute,
private _cmsService: CmsService,
private _router: Router) {
}

ngOnInit() {
this._cmsService.getcmsConsultAbout()
.subscribe(data =>{ this.data = data }
, error => this.errorMessage = error);
}

请任何人帮助我,我陷入了这个问题。我看到了很多与此相关的问题,但没有那么有用并解决我的查询,提前致谢

最佳答案

{ path:"**", component: HomeComponent,pathMatch: 'full' },

将此行移至最后:

RouterModule.forRoot([
{ path:"about", component: AboutComponent },
{ path:"contact" , component: ContactComponent }
{ path:"**", component: HomeComponent,pathMatch: 'full' },
])

What it does is , path:"**" this will consider all the paths , no matter what you enter in url, it is being used for 404 page.

path:"**" should be path:"" for home page url , use path:"**" for your 404 page

理想情况下,您的路线应如下所示:

RouterModule.forRoot([
{ path:"", component: HomeComponent,pathMatch: 'full' },
{ path:"about", component: AboutComponent },
{ path:"contact" , component: ContactComponent }
{ path:"**", component: ErrorComponent },
])

希望这能消除您的所有疑虑。

关于 Angular 组件在路线更改时不会重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275600/

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