How to get URL parameter in angular 10+ asynchronously?

  angular, typescript

I’m trying to get a URL GET parameter using async/await, the logic is that if the loc parameter is not sent to the actual page, then the locale will be calculated. Here’s the code:

private loc: string[] = [];

    private route: ActivatedRoute,
    private http: HttpClient
) { }

async ngOnInit() {
    await this.getLoc();

private async getLoc() {
    var country: string | any;
    var locStr: string | null = await this.route.snapshot.queryParamMap.get('loc');

    if (locStr == null || locStr == '' ) { // There's no loc in URL
      if (navigator.language.includes('-')) { // navigator.language ~ 'es-MX'
        var locale: string[] = navigator.language.split('-')
        this.loc = [locale[0], '', locale[1]]
      } else { // navigator.language ~ 'es'
        await this.http.get("")
        .pipe(map((json: any): 
            Object => {
              return (json['alpha2'] as string)
              response => {
                country = response;
              err => console.error(err));
        this.loc = [navigator.language, '', country]
    } else { // There's loc in URL
      this.loc = locStr.split('_')

The first console.log(locStr) outputs null, and the last console.log(this.loc) outputs my locale using the API or navigator.language, although the URL has a different locale parameter localhost:4200/?loc=en_LSM_US.
I think the problem is the compiler that isn’t waiting for await this.route.snapshot.queryParamMap.get('loc'); and it continues running everything else.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.