Created
March 16, 2020 16:21
-
-
Save christo8989/148ccaa9dc89d3d34ca3a935de69ea51 to your computer and use it in GitHub Desktop.
Angular ParameterService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from "@angular/core" | |
import { ActivatedRoute, ActivatedRouteSnapshot } from "@angular/router" | |
@Injectable({ providedIn: "root" }) | |
export class ParameterService { | |
constructor(private route: ActivatedRoute) { } | |
get(property: string, defaultValue: string = null): string { | |
const value = this.findProperty(this.route.root.snapshot, property) | |
return value || defaultValue | |
} | |
getNumber(property: string, defaultValue: number = null): number { | |
const value = this.findProperty(this.route.root.snapshot, property) | |
const numberValue = Number(value) | |
const valueIsEmptyOrNull = (value || "").trim() == "" | |
const valueIsNaN = numberValue != numberValue | |
return valueIsEmptyOrNull || valueIsNan ? defaultValue : numberValue | |
} | |
private findProperty( | |
snapshot: ActivatedRouteSnapshot, | |
property: string | |
): string | null { | |
const value = snapshot.paramMap.get(property) | |
if (value) { | |
return value | |
} | |
for (let i = 0; i < snapshot.children.length; ++i) { | |
const child = snapshot.children[i] | |
const childValue = this.findProperty(child, property) | |
if (childValue) { | |
return childValue | |
} | |
} | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment