New in Angular 4 - Router-ParamMap

06.05.2017 Stefan Welsch
Mobile Tech angular handson

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

class MyComponent {
 sessionId: Observable<string>;
 
 constructor(private route: ActivatedRoute) {}
 
 ngOnInit() {
   this.sessionId = this.route
     .queryParams
     .map(params => params['session_id'] || 'None');
 }
}

The new approach

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 - pioneer, stuntman, mentor. As the founder of b-nova, Stefan is always looking for new and promising fields of development. He is a pragmatist through and through and therefore prefers to write articles that are as close as possible to real-world scenarios.