首页 文章

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

提问于
浏览
7

目前,当我从路线刷新页面时

http:// localhost:4200 /反馈

它停留在同一条路线上 . 但我希望路由重定向到

http:// localhost:4200

我看到有人问过如何实现刷新以保持同一条路线 . 所以我想,默认角度应该在浏览器刷新时重定向到主页 . 知道为什么我的角度默认项目会这样做吗?

下面是我的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 { }

2 回答

  • 2

    正如Chris Sharp所说,你的应用正在做它应该做的事情,路由到url指向的地方,因为你没有告诉它 .

    你可以做的是,你可以在 OnInit 中重定向到root . 这意味着当(重新)初始化应用程序时,您将被重定向到根页面 .

    export class AppComponent { 
      constructor(private router: Router) {}
    
      ngOnInit() {
        this.router.navigate([''])
      }
    }
    
  • 21

    导入路由器

    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*/']) 
      }
    }
    

相关问题