Search code examples
angularangular-router

How to get URL parameter in angular 10+ from a component that's not a router-outlet?


I'm trying to get a URL GET parameter named 'loc' when visiting localhost:4200/?loc=en_LSM_US. The method's logic is that if the loc parameter is not sent to the actual page, then the locale will be calculated.

I'm trying to get the parameter using this.route.snapshot.queryParamMap.get('loc'); but since the actual component is not a router outlet, the route is null.

The appComponent looks like this:

<body>
  <app-header></app-header>
  <router-outlet></router-outlet>
  <app-footer></app-footer>
</body>

Here's the code of <app-footer>:

private loc: string[] = [];

constructor(
  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
    console.log(locStr);
    if (navigator.language.includes('-')) { // navigator.language ~ 'es-MX'
      var locale: string[] = navigator.language.split('-')
      this.loc = [locale[0], '', locale[1]]
    } else { // navigator.language ~ 'es'
      country = await this.http.get("https://api.ipgeolocationapi.com/geolocate/")
      .pipe(map((json: any): 
        Object => {
          return (json['alpha2'] as string)
        })).toPromise();
      this.loc = [navigator.language, '', country]
    }
  } else { // There's loc in URL
    this.loc = locStr.split('_')
  }
  console.log(this.loc)
}

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.


Solution

  • Using Location from @angular/common, you can get the current path using Location.path().

    And with HttpParams from @angular/common/http, you can parse the http parameters from a string using new HttpParams({ fromString: "string" }).

    So, doing:

    constructor(
      private Location:Location
    ) { }
    
    ngOnInit() {
      console.log(new HttpParams({ fromString: this.Location.path()}))
    }
    

    should print in your webconsole something like: /current?param=value&etc=0, where /current would be your actual route and any parameters would after the ?. So just sanitizing the string eliminating the chars from 0 to ? and then passing the string to HttpParams would do the trick.