Angular 5 - 刷新浏览器后将页面重定向到主页

28

目前,当我从如下路由刷新页面时:

http://localhost:4200/feedback

它仍停留在同一路由上。但是我希望该路由重定向到:

http://localhost:4200

我看到有人问如何实现保持在相同路由的刷新。所以,我猜想,默认情况下Angular应该在浏览器刷新时将其重定向到主页。任何想法为什么我的Angular默认项目会出现这种情况吗?

下面是我的AppRoutingModule:

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

import { SmileyFeedbackComponent } from '../smiley-feedback/smiley-feedback.component';
import { FeedbackFormComponent } from '../feedback-form/feedback-form.component';
import { ThankYouComponent } from '../thank-you/thank-you.component';

const routes: Routes = [
  { path: '', redirectTo: '/smiley', pathMatch: 'full' },
  { path: 'smiley', component: SmileyFeedbackComponent },
  { path: 'feedback', component: FeedbackFormComponent },
  { path: 'thank-you', component: ThankYouComponent }
];

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

路由器正在执行您的路由指示它要执行的操作。如果您想返回根目录,则需要重定向。如果您这样做,那么您将如何访问“反馈”路由? - Chris Sharp
@ChrisSharp,实际上我不需要任何人通过在浏览器URL中键入路由来访问它。AJT_82的下面代码可以解决这个问题。我是Angular的新手。你能告诉我RouterModule和Router之间的区别吗?我的理解是RouterModule就像Router的构造函数,而我需要使用Router进行任何与路由相关的操作。这正确吗? - simplelenz
3个回答

66

正如Chris Sharp所提到的,你的应用正在按照URL指向的位置进行路由,因为你没有告诉它要做什么不同的事情。

你可以在app.component中的OnInit中重定向到根目录。这意味着当应用程序被(重新)初始化时,你将被重定向到根页面。

export class AppComponent { 
  constructor(private router: Router) {}

  ngOnInit() {
    this.router.navigate([''])
  }
}

1
@JT_82,这个可以用。谢谢。你能简要告诉我RouterModule和Router的区别吗? - simplelenz
3
使用RouterModule提供路由到您的应用程序,而使用Router执行实际路由 :) - AT82
这里的 AppComponent 是根组件,其 HTML 文件包含 <router-outlet>,路由组件将在此处呈现。由于它不会被重新创建,因此 AppComponentngOnInit() 方法不会再次被调用。 - j4rey
有什么想法为什么本地可以工作,但部署后就不行了吗? - new_programmer_22

12

导入路由器

import { Router } from '@angular/router';

在构造函数中初始化路由器

export class LoginComponent implements OnInit {
 constructor(private router:Router) {}
  loginCheck() {
    /*Your HTTP REQUEST HERE */
    this.router.navigate(['/*Your Path Here*/']) 
  }
}

-8
如果您需要在Angular 8中重新加载页面,请按照以下步骤操作,这对我很有效。
<a href="/page">Go to page</a>

这是关于HTML的,尝试从TS/JS的角度添加代码。 - Nithin P.H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接