Subscribing to Route Params in Angular

Sam Julien
InstructorSam Julien

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

There are two different ways to access route parameters in Angular components. One is through the route snapshot and the other is by subscribing to the route paramMap. When do you use each? In this lesson, we'll learn that trying to change and access a route parameter in the same component is the key to knowing when to subscribe to the paramMap instead of just using the snapshot.

Lecturer: [0:00] there are two different ways that we can access route parameters in components. Right now we're using this route snapshot, I'm just getting the route parameter once during the ngOnInit() life-cycle hook.

[0:14] The other way that we could get this route param is by subscribing to an observable of the paramMap. Why would we want to do this? In this example, we're only getting the route parameter when we click on one of these links in the account component.

[0:30] What would happen if I moved that navigation from this account component? I'll just copy that and I'm just going to drop it into the account-detail.component template. Now if I click on one of these links, you can see that even though the parameter is changing inside of the URL bar here, it's not changing inside of the component.

[0:57] This is where we would need to subscribe to an observable. Let's make that change. I can go back over to the account detail component here. Instead of doing this with the snapshot, I'm going to delete this and I'm going to delete the snapshot and just subscribe to the paramMap. I'm going to say paramMap.subscribe.

[1:20] We're going to be getting params here and it's going to be of the type paramMap. I'm going to import that and then in our function here, I'm going to set our ID equal to params.get ID like we did before. I'm going to add the plus here to coerce that to a number.

[1:41] Now, if I go over and click on these links, you can see that the template is updating at the same time that the URL bar is. That's the other method that we would use to access route parameters inside of our components. The key difference here is that we're trying to access the route param in the same component that we're also changing that route param.

[2:04] That's the key to when you would use the observable subscription here.