2

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?

Graham
  • 7,431
  • 18
  • 59
  • 84
Vinz and Tonz
  • 3,487
  • 5
  • 21
  • 32

3 Answers3

2

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.

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
shmck
  • 5,129
  • 4
  • 17
  • 29
  • Thank you so much for the answer . Is their a way i can do dynamic routing . Navigate to a route after checking a condition ? Do you have any examples that does dynamic routing with latest version of angularjs 2.0 (..alpha.27) ? – Vinz and Tonz Jun 21 '15 at 11:22
  • 1
    [A route authentication example using alpha.26](https://github.com/auth0/angular2-authentication-sample) – shmck Jun 22 '15 at 01:09
  • Is it possible to trigger routing from javascript. like $state.go() in angularJS. I 've tried location.go in angular 2 but not working. – abhilash Oct 20 '15 at 11:10
  • FYI, the link to the example is dead. – Evan Plaice Oct 26 '15 at 09:48
  • @shmck can we provide path,as,component and router-link dynamically (as angular variable) ? if yes then how ? – Pardeep Jain Nov 19 '15 at 06:40
2

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);
    }
}
Quy Tang
  • 3,929
  • 1
  • 31
  • 45
  • Hi Peter, When you change route do you find that It jumps back to the original route? When I change route to dashboard it straight away returns to login view. Any idea why this occurs? – AngularM Dec 13 '15 at 16:29
  • Could you please show some of your code? Maybe there is a bug in your code that makes your route redirect to that route. – Quy Tang Dec 14 '15 at 06:57
0

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
danday74
  • 52,471
  • 49
  • 232
  • 283