0

I'm trying to make a helper to get some URL param for me, using ActivatedRoute.

The normal way, injecting ActivatedRoute on component, is working fine, like this:

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 want to create a helper file with some getIdFromUrl() function that returns the ID string or an empty string, this way:

import { ActivatedRoute } from "@angular/router";

export function getIdFromUrl(): string
{
    var route = new ActivatedRoute();
    var id = route.snapshot.paramMap.get("id");
    return id !== null ? id : "";
}

But can't make this to work and can't figure out why.

Can someone help me with this?

Thanks!

1
  • @H3AR7B3A7 this works, but I still need to inject ActivatedRoute on my component's constructor, to pass it as parameter to the getIdFromUrl... Do you know if there's another way that I don't need to inject it on component? Commented Aug 31, 2021 at 19:44

1 Answer 1

0

Outlets have their own ActivatedRoute instance so you won't be able to get it from elsewhere as if it were a singleton.

However with Router it should be possible to do something like this. Here I've done a quick example with a service that can return a param retrieved from the url on one component and one that uses ActivatedRoute.

https://stackblitz.com/edit/angular-ivy-juypes?file=src/app/app.module.ts

Would a similar service work for you or do you not want to inject a service either?

@Injectable()
export class GetParamFromRouteService {
  constructor(private router: Router) {}

  getIdFromRoute(): string {
    return this.router.routerState.snapshot.root.children[0].params['id'] || '';
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.