Angular 2 routing

2.9k views Asked by At

I searched the net to get an example of angular2 router that changes browser urls. All examples that are there doesn't change browser urls when we change different routes. Can you give me a small example in ES6 to demonstrate this?

3

There are 3 answers

5
shmck On BEST ANSWER

An example.

On a Component class:

@RouteConfig([
  { path: '/',          name: 'home',      component: Home },
  { path: '/dashboard', name: 'dashboard', component: Dashboard },
  { path: '/todo',      name: 'todo',      component: Todo }
])
export class App {}

name is not necessary, but can be used to provide an alias.

In the template:

<a router-link="home">Home</a>

Note that router-link must exist on an <a> tag.

0
danday74 On

in your unit test you would do something like ..

spyOn(instance.router, 'navigateByUrl'); // first thing inside it block

expect(instance.router.navigateByUrl).toHaveBeenCalledWith(uri); // near end of it block when you would have expected the navigation to have happened
2
Quy Tang On

After digging into Angular2 source code, I figured out one way to get dynamic routing to work. Let's see this example:

import {Router} from 'angular2/router';
@Component({
    ...
})
export class SampleComponent {
    public router: Router;

    constructor(router: Router) {
        this.router = router;
    }

    goTo(uri) {
        this.router.navigateByUrl(uri);
    }
}