Skip to content

Instantly share code, notes, and snippets.

@ovrmrw
Created May 27, 2018 05:26
Show Gist options
  • Save ovrmrw/04c4e63c65545bb9bd7af8b4752d9844 to your computer and use it in GitHub Desktop.
Save ovrmrw/04c4e63c65545bb9bd7af8b4752d9844 to your computer and use it in GitHub Desktop.
type ParamValue = string | number | boolean;
export interface ParamsObject {
[key: string]: ParamValue | ParamValue[];
}
export class RouterWrapper {
private _location: Location;
private _URL: typeof URL;
constructor(private $location: ng.ILocationService, private $route: ng.route.IRouteService, $window: ng.IWindowService) {
this._location = $window.location;
this._URL = $window.URL;
}
navigate(url: URL | string, params?: URLSearchParams | ParamsObject | string): void {
const _url = this.getURL(url);
const _params = this.getURLSearchParams(params);
_url.search = _params.toString();
const {pathname, search, hash} = _url;
const routerUrl = pathname + search + hash;
if (this._location.href === _url.href) {
this.reload();
} else {
this.$location.url(routerUrl);
}
}
reload(): void {
this.$route.reload();
}
getCurrentURL(): URL {
return new this._URL(this._location.href);
}
getURL(url: URL | string): URL {
if (url instanceof URL) {
return url;
} else {
const origin = this._location.origin;
if (url.startsWith(origin)) {
return new this._URL(url);
} else {
return new this._URL(origin + url);
}
}
}
getCurrentURLSearchParams(): URLSearchParams {
return this.getCurrentURL().searchParams;
}
getURLSearchParams(params?: URLSearchParams | ParamsObject | string ) {
if (!params) {
return new URLSearchParams();
} else if (params instanceof URLSearchParams) {
return params;
} else if (typeof params === 'string') {
return new URLSearchParams(params);
} else {
return Object.keys(params).reduce((p, key) => {
const value = params[key];
if (value instanceof Array) {
value.forEach(v => p.append(key, '' + v));
} else {
p.append(key, '' + value);
}
return p;
}, new URLSearchParams())
}
}
}
angular.module('app').service('RouterWrapper', RouterWrapper);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment