1

So i'm trying to get the the value from the url and i want to do this with promise and async/await. But when i run this in both chrome and opera it just stands and wait on that point. Anyone got that can point me in the right direction or am i doing something wrong ?

My component implements : implements OnInit

Constructor :

constructor(private route: ActivatedRoute, 
            private zone : NgZone
            ) 
            {

            }

The imports :

import { Component, OnInit, NgZone } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';

Methods:

async ngOnInit() 
{
    var Id : string = await this.getIdFromUrl(); 
}


getIdFromUrl() : Promise<string> 
    {
        return this.route.params.map(params => 
        {   
            return params['id']; 
        }).toPromise();  
    }
Nyranith
  • 367
  • 2
  • 6
  • 15
  • Have a look into [**this answer**](https://stackoverflow.com/questions/44221485/angular2-routing-with-parameters-fails/44221712#44221712) – Aravind May 28 '17 at 11:08

1 Answers1

5

ngOnInit is supposed to return void. Making it async indicates XY problem, this deviates from the interface because async ngOnInit returns a promise and results in potentially uncaught promise errors. If there are promises that should be resolved on initialization, they can be made resolvers.

route.params is an observable because it emits multiple values when navigating to the same route with different params. It isn't completed and calling toPromise() on it will result in pending promise. For this reason observables aren't interchangeable with promises.

Initial param value is already known on component initialization and is synchronous. It is reachable with ActivatedRouteSnapshot interface,

ngOnInit() {
    const id: string = route.snapshot.params.id;
}

Depending on how a route is used and route reuse strategy, this may not work as expected, because subsequent param changes won't be handled. It is generally preferable to stick to route.params observable for this reason.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks for your time, it fixed a lot :) – Nyranith May 28 '17 at 12:47
  • 1
    unfortunately, this doesn't work for me. `const syncRoute: any = this._route.snapshot; ` shows no params, I have to listen to them asynchronously with `this._route.queryParamMap.subscribe(parameter => {.. ` and therefore have massive racing conditions in my ngOnInit() . The URL is simply called, no changing values in it whatsoever. – Nikita Fuchs Aug 16 '19 at 14:23
  • @NikitaFuchs This depends on your case. There can be scenarios when a param won't be available on component init. See the remark, *Depending on how a route is used and route reuse strategy, this may not work as expected, because subsequent param changes won't be handled*. – Estus Flask Aug 17 '19 at 20:32