Angular 5 - redirect page to homepage on browser refresh

五迷三道 提交于 2019-11-27 12:17:34

问题


Currently, when I refresh a page from a route like

http://localhost:4200/feedback

it stays on the same route. But I want the route to redirect to

http://localhost:4200

I saw people have asked how to implement the refresh to stay on the same route. So I guess, the default angular should redirect to homepage on browser refresh. Any idea why my angular default project does this otherwise?

Below is my 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 { }

回答1:


As mentioned by Chris Sharp, your app is doing exactly what it should do, routing to the place that the url is pointing to, since you have not told it otherwise.

What you can do, is that in your app.component you can in OnInit redirect to root. This then means that when app is (re)initialized, you are being redirected to root page.

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

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



回答2:


Import Router

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

Initiate Router in Constructor

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



回答3:


If you need reload page in angular 8 then do following, it worked for me.

<a href="/page">Go to page</a>


来源:https://stackoverflow.com/questions/47234250/angular-5-redirect-page-to-homepage-on-browser-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!