Reputation: 61
I'm building an app in angular 6 and i'm looking for a functionality with which i can use whatever the user is typing in the Browser's address bar in the site,
For example:
User enters domain "myproject.example/5/cool
"
then the website should give output "User 5
is soo cool
!"
Is there a way to read what the user types in the URL?
Thanks in advance
Upvotes: 1
Views: 605
Reputation: 541
Yes, it's possible to read the url in the address bar. There's two way to do it : with the ActivatedRoute
and with Router
.
ActivatedRoute
will require a app-routing.module.ts
with the elements you want to display in your component:
{ path: ':customerId/:state', component: YourComponent }
And, in your component :
constructor(private route: ActivatedRoute) {
this.route.paramMap.subscribe(params => {
this.customerId = params.get('customerId');
this.state = params.get('state');
});
}
You'll only need to construct your output with customerId
and state
.
If you don't want to use the routing (or you can't for whatever reason), you can also use Router
to read the url. You'll juste need to parse it :
constructor(private router: Router) {
this.href = this.router.url;
}
Upvotes: 1