read

angular-logo It is quite common for developers coming from a different background to get confused about Angular Router and How to retrieve URL params in angular 7? It is a fairly simple and straightforward task and that’s what you are gonna see in action in this article. Let’s Start!

Scope

We will retrieve an id present in param from the URL and will make an API request using that retrieved id.

Setting up routes

What we want is to show the user details of an order when they open a specific page in our app. We have created a component named OrderDetailComponent for the showing order’s detail. Next Step is to define a route in our angular app. If you are using Angular CLI, It should be in a file named app-routing.module.ts in yourProject/src/app. To add a route with dynamic params, add this to your file -

{
    path: ‘orders/:id’,
    component: OrderDetailComponent,
},

This tells your app to render the OrderDetailComponent whenever the URL https://www.xyz.com/orders/{anyId} is accessed. For example, https://www.xyz.com/orders/1 is for order with id 1.

ActivatedRoute

In order to access the params from the URL, you need to import ActivatedRoute module from the @angular/router -

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

Inject it in the constructor of your component like any other angular. service. Here we are injecting it in OrderDetailComponent -

export default class OrderDetailComponent implements OnInit {
   constructor(private route: ActivatedRoute) {}
   ...
}

Then we will retrieve the id in ngOnInit (lifecycle hook) of our component. If you are not familiar with the Lifecycle hooks of an angular component, I will recommend going through Angular Lifecycle Hooks. There are two common methods to achieve that, One is usingsnapshot and other is using the subscription of the ActivatedRoute.

Snapshot

You can retrieve the id from Snapshot of the ActivatedRoute instance we injected in our constructor like this -

export default class OrderDetailComponent implements OnInit {
   constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        const selectedId = _Number_(this.route.snapshot.params['id']);
    }
}

Subscription

You can also retrieve the id by subscribing to the ActivatedRoute like this -

export default class OrderDetailComponent implements OnInit {

    constructor(private route: ActivatedRoute) {}
    selectedId: number;

    ngOnInit(){
        this.route.paramMap.subscribe(params => {
            this.selectedId = Number(params.get('id'));
        });
    }
}

The advantage of using this method is whenever the URL params are changed you will receive the updated value of id and value of selectedId will be updated as well.

Now you can call your API for the data i.e. Order Details using the id we just retrieved from the URL.

export default class OrderDetailComponent implements OnInit {

    constructor(private route: ActivatedRoute) {}
    selectedId: number;

    ngOnInit(){
        this.route.paramMap.subscribe(params => {
            this.selectedId = Number(params.get('id'));
            /* Make the API call using this.selectedId to fetch the details of the order*/
        });
    }
}

If you are familiar with RxJs, You can also use switchMap operator like -

export default class OrderDetailComponent implements OnInit, OnDestroy {

    constructor(
        private route: ActivatedRoute,
        private orderApiService: OrderAPIService //some service to do the networking
    ) {}
    orderDetails: Order
    subscription: Subscription

    ngOnInit() {
        this.subscription = this.route.paramMap.pipe(
            switchMap(params => {
                const  selectedId = Number(params.get('id'));
                return this.orderApiService.getOrder(selectedId);
            })
        ).subscribe(orderDetails => {
            this.orderDetails = orderDetails
        })
    }

    ngOnDestroy(){
        this.subscription.unsubscribe()
    }
}

Note: ActivatedRoute.paramMap is a hot observable stream, so you need to unsubscribe from it as shown in the example above

Conclusion

We can retrieve URL parameters using either ActivatedRoute snapshot or by subscribing to the ActivatedRoute params depending upon the need of the situation. Use snapshot for one-time retrieval or use subscription if the URL can change dynamically within the component.

Feel free to chat in comments! Happy Coding!

Blog Logo

Vishal Gosain


Published

Image

Hot Cocoa Software

Blogs written by our developers.

Back to Overview