New in Angular 4 - Router-ParamMap

06.05.2017Stefan Welsch
Mobile Angular Hands-on

In order to be able to use the route and query parameters of an associated route, there is now the option of using paramMap.

The traditional approach

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyComponent {
 sessionId: Observable<string>;
 
 constructor(private route: ActivatedRoute) {}
 
 ngOnInit() {
   this.sessionId = this.route
     .queryParams
     .map(params => params['session_id'] || 'None');
 }
}

The new approach

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyComponent {
 sessionId: Observable<string>;
 
 constructor(private route: ActivatedRoute) {}
 
 ngOnInit() {
   this.sessionId = this.route
     .queryParamMap
     .map(paramMap => paramMap.get('session_id') || 'None');
 }
}

Are there any advantages?

Yes, because using paramMap ensures that it is type-safe. Because in the previous version there was an insecure type (type params = {[key: string]: any}), which meant that the values could have all possible types. Instead, the new approach returns either a string or an array of strings. Depending on which method is used (*paramMap.get(): string or paramMap.getAll (): string []) *)


This text was automatically translated with our golang markdown translator.

Stefan Welsch

Stefan Welsch – Pionier, Stuntman, Mentor. Als Gründer von b-nova ist Stefan immer auf der Suche nach neuen und vielversprechenden Entwicklungsfeldern. Er ist durch und durch Pragmatiker und schreibt daher auch am liebsten Beiträge die sich möglichst nahe an 'real-world' Szenarien anlehnen.