Vinz and Tonz
Vinz and Tonz

Reputation: 3587

Angular 2 routing

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?

Upvotes: 2

Views: 2950

Answers (3)

danday74
danday74

Reputation: 56986

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

Upvotes: 0

shmck
shmck

Reputation: 5609

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.

Upvotes: 2

Quy Tang
Quy Tang

Reputation: 3979

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);
    }
}

Upvotes: 2

Related Questions