5
votes

I have an angular 2 app with the following routes:

@RouteConfig([
new Route({ path: '/', component: Home, name: 'Home', useAsDefault: true}),
new Route({ path: '/employees', component: ViewEmployees, name: 'ViewEmployees'}),
new Route({ path: '/employees/add', component: AddEmployee, name: 'AddEmployee'}),
])

among others. When I change routes in the following way:

<a [routerLink]="['ViewEmployees']">View Employees</a>

There are no issues. I can change routes in this way from either the home page or the AddEmployee route. The issue comes when I'm in the AddEmployee route and try to change routes in a programmatic way like this:

import {Router} from 'angular2/router';
...
constructor(private _router:Router) {}
...
navigate() {
    this._router.navigate(['ViewEmployees']);
}

it doesn't work. It sends me to the ViewEmployees view and then reloads the entire app. If I do that same programmatic route change from the Home component I don't have any issues; the app doesn't reload.

Does anyone have any ideas why it would do this in just this one case? I need it to work so that I can save the employee that's added and then go back to the employee list view.

Thanks in advance for the help!

3
Were you able to solve this yeat? I am having same issue.Marin Petkov

3 Answers

3
votes

Do you call navigate() from within a <form> Tag?

I had the same Problem. There exist some issues describing this behavior on Angular2s GitHub but they are all closed because they belong to the old router. The page reload seems to occur when you use router.navigate() inside a function called by a submit button inside a form. This can cause the browser to append a ? at the end of the URL and reload it.

The solution is very simple: Just return false at the end of your navigate() function. This prevents the bowser to use it's default action when submitting forms. Usually angular stops such default behavior but strangely not in this case.

1
votes

Have you set the <base href>?

As mentioned in the Router guide

Add the following code to your index.html after the opening head tag:

<base href="/">

1
votes

From RouterLink docs:

The first route name should be prepended with /, ./, or ../. If the route begins with /, the router will look up the route from the root of the app. If the route begins with ./, the router will instead look in the current component's children for the route. And if the route begins with ../, the router will look at the current component's parent.

Use:

<a [routerLink]="['/ViewEmployees']">View Employees</a>