I'm attempting to create a helper function using ActivatedRoute to retrieve URL parameters for me.
The traditional method of injecting ActivatedRoute into the component has been successful, as shown below:
constructor(
private route: ActivatedRoute,
private api: MyApiService
) { }
ngOnInit(): void {
this.api.getData(this.route.snapshot.paramMap.get("id") || "").subscribe((data: any) => {
console.log(data);
}, (error: any) => {
console.error(error);
})
}
Now, I am trying to implement a helper file with a getIdFromUrl()
function that should return the ID string or an empty string. Here is my attempt:
import { ActivatedRoute } from "@angular/router";
export function getIdFromUrl(): string
{
var route = new ActivatedRoute();
var id = route.snapshot.paramMap.get("id");
return id !== null ? id : "";
}
However, I am encountering issues and unable to identify the root cause of the problem.
If anyone can provide assistance, it would be greatly appreciated.
Thank you!