Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 redirects to root path when browser reloads

The page is currently http://localhost:4200/foo.

Case 1: If I press the browser's reload button or type the same url in the browser, the page redirects to http://localhost:4200 (root path).

I'd like the page keeps in the same url (http://localhost:4200/foo).

Case 2: If I type http://localhost:4200/foo (same url) the page redirects to http://localhost:4200 (root path).

I also would like the page keeps in the same url I've typed (http://localhost:4200/foo).

Otherwise, if the page is http://localhost:4200 and I type http://localhost:4200/foo, it works fine. I can navigate by url paths normally. The problem is only when I go to the same path.

My root path in app.module.ts is:

const rootRouting: ModuleWithProviders = RouterModule.forRoot([
    {
        path: 'foo',
        loadChildren: './foo/foo.module#FooModule'
    },
    {
        path: '',
        loadChildren: './bar/bar.module#BarModule'
    },
], { });

And my path in foo.module.ts is:

    const fooRouting: ModuleWithProviders = RouterModule.forChild([
      {
        path: 'foo',
        component: FooComponent
      }
    ]);

OBS: This question Angular 5 - redirect page to homepage on browser refresh wants exactly the opposite of mine. Now, I don't know what is the Angular default behavior for this cases.

Edit after DiPix's correction:

My root path in app.module.ts is:

const rootRouting: ModuleWithProviders = RouterModule.forRoot([
    {
        path: 'foo',
        loadChildren: './foo/foo.module#FooModule'
    },
    {
        path: '',
        loadChildren: './bar/bar.module#BarModule'
    },
], { });

And my path in foo.module.ts is:

    const fooRouting: ModuleWithProviders = RouterModule.forChild([
      {
        path: '',
        pathMatch: 'full',
        component: FooComponent
      }
    ]);

Edit 2:

Debugging with google chrome, I've set "Preserve log".

Testing with any other site, if you are at "www.anydomain.com/path" and you reload the browser, chrome writes "Navigated to 'www.anydomain.com/path'.

Testing with my app, if I am at "http://localhost:4200/foo" and I reload the browser, chrome writes "Navigated to 'http://localhost:4200/'.

The browser navigates to root path!

like image 867
Igor Torres Avatar asked Feb 27 '18 22:02

Igor Torres


1 Answers

You need to define some routes at the root of your application. Something like this:

const routes: Routes = [
  { path: 'foo', component: FooComponent},
  { path: '', redirectTo: '/foo', pathMatch: 'full' },
  { path: '**', component: FooComponent }
];

These routes would go where you defined your forRoot() method which from you code looks like:

const rootRouting: ModuleWithProviders = RouterModule.forRoot(routes);

like image 113
Narm Avatar answered Oct 17 '22 08:10

Narm