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

sim*_*enz 21 typescript angularjs-ng-route angular

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

HTTP://本地主机:4200 /反馈

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

HTTP://本地主机: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 { }
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 43

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

你能做什么,就是app.component你可以OnInit重定向到root.这意味着当(重新)初始化应用程序时,您将被重定向到根页面.

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

  ngOnInit() {
    this.router.navigate([''])
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,使用RouterModule,您可以提供到应用程序的路由,并使用路由器进行实际路由:) (2认同)

Ana*_*n K 7

导入路由器

import { Router } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

在构造函数中启动路由器

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