Skip to content

Instantly share code, notes, and snippets.

@hartraft
Created November 28, 2017 16:06
Show Gist options
  • Save hartraft/69cd98101543d28e95d91de799472452 to your computer and use it in GitHub Desktop.
Save hartraft/69cd98101543d28e95d91de799472452 to your computer and use it in GitHub Desktop.
Angular 2+ subscribing to query and route params. From https://github.com/angular/angular/issues/13804 there is no need to unsubscribe the observables. https://angular.io/docs/ts/latest/guide/router.html#!#reuse
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import 'rxjs/add/observable/combineLatest';
import { Observable } from 'rxjs/Observable';
@Component( {
selector: 'test-route',
templateUrl: './test-route.component.html'
} )
export class TestRouteComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
let combinedObservables = Observable.combineLatest(this.route.params, this.route.queryParams, ( params, queryParams) => ({ params, queryParams }));
combinedObservables.subscribe( combinedParams => {
console.log( combinedParams.queryParams['filter'] );
console.log( combinedParams.queryParams['sort'] );
console.log( combinedParams.queryParams['desc'] === 'true' );
console.log( combinedParams.params['id'] );
this.callService();
});
// Subscribe only route parameters (e.g /person/:id => /person/23)
// this.route.paramMap
// .subscribe( params => {
// console.log(params.get( 'id' ));
// this.callService();
// } );
    // Subscribe only query parameters (e.g /person/23?filter=employee&sort=firstname&desc=true
// this.route.queryParamMap.subscribe( queryParams => {
// console.log(queryParams.get( 'filter' ));
// console.log(queryParams.get( 'sort' ));
// console.log(queryParams.get( 'desc' ) === 'true');
// this.callService();
// } );
}
callService(): void {
// do stuff with the query / route params
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment