Steps:

  • Configure the routes
  • Add router outlet
  • Add Links

Configure the routes

In app.module.ts

import { RouterModule } from '@angular/router';
//...
imports:[
  //...
    RouterModule.forRoot([
        { path:'', component: HomeComponent },
        { path:'followers/:username', component: ProfileComponent }, //parameter
        { path:'followers', component: FollowersComponent },
        { path:'posts', component: PostsComponent },
        { path:'**', component: NotfoundComponent },  //wildcard
    ])
    //...
]  
1
2
3
4
5
6
7
8
9
10
11
12
13

Add router outlet

in app.conpontent.html

<router-outlet></router-outlet>
1

the router outlet will load the compontent with response to the address we type.

<a routerLink="/followers">followers</a>
<a routerLink="/posts">posts</a>
<a [routerLink]="['/followers', follower.id]">follower </a>
1
2
3

routerLinkActive attribute

show active on click, current is just demonstrate for routerLinkActive is supporting multiple classes.

<li routerLinkActive="active current"> <a RouterLink="/followers">followers</a></li>
<li routerLinkActive="active current"> <a RouterLink="/posts">posts</a></li>
1
2

get route parameter

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {

    //get the parameter map
    this.route.paramMap.subscribe(params => {
        console.log(params)                  // params: {usernames:"32135035132"}
      let id = +params.get('id');     //params.get('id') = get the id of the http://website.com/followers/:id, + sign convert string to number 
      console.log(id);        //log the result id in condole

      let id = this.route.snapshot.paramMap.get('id'); // sure the 
    })

  }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

multiple parameter

 { path:'followers/:id/:username', component: ProfileComponent },
1
<a [RouterLink]="['/followers', follower.id, follower.login]">follower </a>

1
2

query parameters

<a RouterLink="/followers" [queryParams]="{page: 1, order:'newest'}">followers</a>
1
constructor(private router: Router) { }

ngOnInit() {
    this.route.queryParamMap.subscribe();
}
1
2
3
4
5

subscribe to multiple observables

  ngOnInit() {
    Observable.combineLatest([
      this.route.paramMap,
      this.route.queryParamMap
    ])
    .switchMap(combined =>{
      let id = combined[0].get('id');
      let page = combined[1].get('page');

      
      return this.service.getAll()
    })
    .subscribe( followers => this.followers = followers);
1
2
3
4
5
6
7
8
9
10
11
12
13

Programatic Navigation

submit(){
    this.router.navigate(['/followers'],{
        queryParams: { page: 3, order: 'newest' }
    })
}
1
2
3
4
5
Last Updated: 1/14/2019, 12:15:15 AM