Skip to content

Instantly share code, notes, and snippets.

@nivrith
Last active February 1, 2021 22:34
Show Gist options
  • Save nivrith/393265541427fbd3e84e9e207770ed19 to your computer and use it in GitHub Desktop.
Save nivrith/393265541427fbd3e84e9e207770ed19 to your computer and use it in GitHub Desktop.
How to preserve query params globally with angular router
import { PathLocationStrategy, APP_BASE_HREF, PlatformLocation } from '@angular/common';
import { Optional, Inject, Injectable } from '@angular/core';
import { UrlSerializer } from '@angular/router';
@Injectable()
export class PreserveQueryParamsPathLocationStrategy extends PathLocationStrategy {
private get search(): string {
return this.platformLocation?.search ?? '';
}
constructor(
private platformLocation: PlatformLocation,
private urlSerializer: UrlSerializer,
@Optional() @Inject(APP_BASE_HREF) _baseHref?: string,
) {
super(platformLocation, _baseHref);
}
prepareExternalUrl(internal: string): string {
// join path with slashes and baseHref (internal, see angular source :D )
const path = super.prepareExternalUrl(internal);
const existingURLSearchParams = new URLSearchParams(this.search);
// create object literal from an iterator of URLSearchParams (key, value) pair
const existingQueryParams = Object.fromEntries(existingURLSearchParams.entries());
// parse (deserialize) the final url path and get the corresponding url tree for easier data manipulation
const urlTree = this.urlSerializer.parse(path);
const nextQueryParams = urlTree.queryParams;
// merge existing query params with the next route's queryParams
urlTree.queryParams = { ...existingQueryParams, ...nextQueryParams };
// serialise urlTree
return urlTree.toString();
}
}
{
//...
// add `dom.iterable` to make `entries()` method available on Dom iterables (e.g. URLSearchParams)
// see https://github.com/microsoft/TypeScript/blob/66ecfcbd04b8234855a673adb85e5cff3f8458d4/lib/lib.dom.iterable.d.ts#L271
"lib": ["es2017", "dom", "dom.iterable"],
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment