Skip to content

Instantly share code, notes, and snippets.

@balassy
Last active July 16, 2019 17:41
Show Gist options
  • Save balassy/f504720eddab30f6f08652770651762b to your computer and use it in GitHub Desktop.
Save balassy/f504720eddab30f6f08652770651762b to your computer and use it in GitHub Desktop.
Parse a URL in Angular 2, inspired by https://davidsekar.com/angular/parse-url-in-angular2-.
Placeholder for stupid gist naming (https://github.com/isaacs/github/issues/194), find the important parts below.
import { Injectable } from '@angular/core';
import * as urlParse from 'url-parse';
import { ParsedUrl } from './url-parser.types';
export * from './url-parser.types';
@Injectable()
export class UrlParserService {
public parse(url: string): ParsedUrl {
const baseUrl = {}; // Ensures that the parsing is independent from the current location of the browser.
const parseQueryString: boolean = true;
return urlParse(url, baseUrl, parseQueryString);
}
}
export interface ParsedUrl {
protocol: string;
slashes: boolean;
auth: string;
username: string;
password: string;
host: string;
hostname: string;
port: number;
pathname: string;
query: {
[key: string]: string;
};
hash: string;
href: string;
origin: string;
set(key: string, value: string): void;
toString(): string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment