Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Getting route's params with promises

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.

like image 490
Scipion Avatar asked Oct 19 '16 09:10

Scipion


1 Answers

_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())

like image 181
Günter Zöchbauer Avatar answered Sep 21 '22 14:09

Günter Zöchbauer