Search code examples
angularangular2-routingangular-router

angular 2 router hybrid app: url reverts back after navigate


Every route change is rendering the correct component but has issue with path.
For example navigating from /items to /add-item changes and url for a second but then reverts it.
It happens on every page no matter from where to start and where to go.

Navigation

<a routerLink="/add-item">Add item</a>

Main app.routes.ts

export const appRoutes: Routes = [{
    path: 'brokers',
    pathMatch: 'full',
    redirectTo: '/'
},
{
    path: 'sellers',
    pathMatch: 'full',
    redirectTo: '/'
},
{
    path: 'buyers',
    pathMatch: 'full',
    redirectTo: '/'
},
{
    data: { name: 'pageNotFound' },
    path: '**',
    redirectTo: '/404'
}];

home.routes.ts

export const homeRoutes: Routes = [{
    component: HomePageComponent,
    data: { name: 'homePage' },
    path: ''
}

page-not-found.routes.ts

export const pageNotFoundRoutes: Routes = [{
    component: PageNotFoundComponent,
    data: { name: 'pageNotFound' },
    path: '404'
}]

add-item.routes.ts

export const addItemRoutes: Routes = [{
    component: AddItemComponent,
    data: { name: 'addItem' },
    path: 'add-item'
}]

items.routes.ts

export const itemsRoutes: Routes = [{
    component: ItemsComponent,
    data: { name: 'items' },
    path: 'items'
}];

All modules' routes are declared in import section like this

RouterModule.forChild(addItemRoutes)

Main routes

RouterModule.forRoot(appRoutes, { enableTracing: true })

Router tracing gives me no errors and correct urlAfterRedirects on NavigationEnd event.


Solution

  • Just to anyone who will meet the same problem.
    If you have hybrid AngularJS to Angular app you have to keep old $locationProvider settings like $locationProvider.html5Mode({ enabled: true, requireBase: false });
    Otherwise your new Angular routing will meet this issue.

    Or you can switch off Angular.js route manipulation with such a hack

    $provide.decorator('$browser', ['$delegate', ($delegate) => {
    
        $delegate.onUrlChange = () => {};
        $delegate.url = () => {
    
            return '';
    
        };
    
        return $delegate;
    
    }]);