Query parameter always present in URL

February 27, 2025 · 2 min readLucian Ciobanu
Tags:Angular

After successfully building and deploying an Angular web app, we wanted this app to be accessed from another app by a super admin like user and the request was to always have in the URL the query parameter "accountId" with the value related to this super admin user. The challenge was so to always append this id, even if the user changes links or refreshes.

There is not a lot of literature on the web about this but starting from this github comment, I was able to adapt to what I needed as follows:

In app-routing.module.ts, I had to add this to providers:

...
@NgModule({
  providers:[
    {
      provide: LocationStrategy,
      useClass: PreserveQueryAccountIdStrategy //class I created
    }
  ]
})

preserve-query-account-id.strategy.ts

...
@Injectable()
export class PreserveQueryAccountIdStrategy extends HashLocationStrategy {
  private readonly queryParams: string;
  constructor(
    _platformLocation: PlatformLocation,
    @Optional() @Inject(APP_BASE_HREF) _baseHref?: string
  ) {
    super(_platformLocaiton, _baseHref);
    this.queryParams = window.location.search || ''; //getting the query params if used
  }

  override prepareExternalUrl(internal: string): string {
    return `{$internal}{$this.queryParams}`
  }
}

And with this you are always appending the query params if they exist

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery