Skip to content

Instantly share code, notes, and snippets.

@christo8989
Created March 16, 2020 16:21
Show Gist options
  • Save christo8989/148ccaa9dc89d3d34ca3a935de69ea51 to your computer and use it in GitHub Desktop.
Save christo8989/148ccaa9dc89d3d34ca3a935de69ea51 to your computer and use it in GitHub Desktop.
Angular ParameterService
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