简体   繁体   中英

Angular 4 Redirecting to Root on Refresh

I have an Angular 4 single page application. When I refresh the page, or enter a valid URL into the browser, I get redirected to the app's root route.

I've changed my nginx config to redirect all requests to /index.html, which fixed my initial issue of getting 404s on browser refresh.

server {
    listen  80;

    server_name bla.com www.bla.com

    location / {
        root  /home/admin/web/bla.com/public_html;
        index  index.html index.htm;
        try_files $uri $uri/ =404;
    }

    error_page 404 /index.html;

    error_page  500 502 503 504  /50x.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    location = /50x.html {
        root  /usr/share/nginx/html;
    }
}

** Edit **

Angular routing is simply handled by the RouterModule:

// ...

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

// ...

const appRoutes: Routes = [
  { path: '', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'clients', component: ClientsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddClientComponent, canActivate: [AuthGuard]}
  ]},
  { path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddProjectComponent, canActivate: [AuthGuard] }
  ]},
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'invoices', component: InvoicesComponent, canActivate: [AuthGuard], children: [
    { path: 'invoices/new-invoice', component: NewInvoiceComponent, canActivate: [AuthGuard] }
  ]}
];

I don't really want to use HashLocationStrategy, so is there a way I can get Angular to serve the correct page when the browser refreshes or when a URL is entered?

我想[AuthGuard]会给您带来麻烦。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM