Angular2 Getting route's params with promises

angular, typescript

Solution

`_route.params` emits more than one event. When a route change only changes the parameter value of a route then the component is not re-created by the router but instead just another `params` value emitted.

Therefore using `toPromise()` is probably not a good idea but it's possible, for example using `first()` so that the observable completes after the first event and therefore also the promise returned by `toPromise()` completes.

Without `.first()` the promise completes when you navigate away from the route (not verified).

constructor(private _route: ActivatedRoute) {}

ngOnInit() {
  this._route.params.first().toPromise().then(data => {
     ...
  })
}

`first` needs to be imported. In newer RxJs version `first` needs to be wrapped in `pipe` like this `pipe(first())`

Problem

Hey I have tried that following bit of code : ``` constructor(private _route: ActivatedRoute) {} ngOnInit() { this._route.params.toPromise().then(data => { ... }) } ``` However it doesn't do anyhting. If I swap `toPromise().then` by `subscribe` it works fine. Any idea why it wouldn't work ? I have used `toPromise().then` in many other places in my project and it works just fine.

Original source