Working with route parameters - lordoftheflies/angular-essential-training GitHub Wiki
Angular provides a way to get information about the currently activated route through a service of type ActivatedRoute. Getting to that information is just a constructor injection away. In the media-item-list.component.ts file, let's add an import statement to bring in activated route from the angular router scoped package. And then we can add it to the constructor parameters, making it private so we can get to it from other methods in the class, naming it ActivatedRoute and setting the type to activatedRoute. The activated route service has a property named param map that is an observable. This observable sends through a param map object that contains the route parameters collected by the router during each route change. That means that we can subscribe to it and get notified anytime the set of route params changes. So in the ngOnInit method, we can remove the existing logic and replace it with a call to this.activatedRoute.paramMap.subscribe. We want to give this a function so we will use an arrow function here and name the parameter paramMap, then the arrow and then the function body. We actually need to do two things here. We want to call the getMediaItems class method but before we do that, we need to do some normalization to the medium first. So we created a default route that would end up having the medium set to the string value all. That will flow through to this code but the mock API will treat that as a medium type if we attempt to send it through. So we need to change medium to an empty string here. If the route param is set to all. Let's create a local variable named medium and get the route param. The paramMap object has a method named get that we can use to request the value of a route parameter by name. So here we can set medium equal to a call to paramMap.get and pass that in a string value of medium. And then we can do an if check where we can lowercase the value of medium and see if it equals all. And if so, we set medium to an empty string. Then we pass in medium to the call to this.getMediaItems. And now if we switch to the browser, we can see the list filter when we click the links.