Search code examples
angularangular-routing

Generate unique URL for every entry in Database in Angular 6


I have a bunch of data inside my MongoDB and I'm using the MEAN stack for my application. So I have a search, where the user can search the database for an entry, let's take a hospital as an example. The user can specify the options for the hospital, and than the system shows the hospitals which meets the criteria. So if the user now clicks on one hospital, they get the full details of it. Opening times, parking possibilities etc. on an extra page / component.

So I'd now like to create a unique link for this specific hospital, so that the user can save that anywhere they want and access it the next time without using the search.

I'd like something like this -> http://mywebsite.com/hospital/california/alameda-hospital

How can I solve this? My component is based on an @Input() which normally holds the hospital information. So now, when the user enters the URL, I need to request my database, get the information needed and fill them into my object hospitalDetails: Object or what would be the correct way?


Solution

  • Use the route parameters in the ngOnInit, and subscribe to the changes, updating the components value:

    constructor( private hospitalService: HospitalService, private route: ActivatedRoute ) // lets say you get the hospital info from the hospitalService via a get
    ngOnInit(){
      this.route.params.subscribe(params => {
          this.hospitalId = params.hospitalId
          this.hospitalService.getHospital(this.hospitalId).subscribe( hospital => {
           this.hospital = hospital
          }
      }
    }
    

    In the router where you define the route:

    { path: "hospital/:state/:hospitalId", component: HospitalDetailsComponent }
    

    This defines the parameters which then might be accessed in the route.params subscription.

    I would just use an hospitalId as universal identifier, but you can combine state and hospital name to acomplish the same thing.

    Edit: You can still use an @Input decorator in your hospital details. The component can work as template component (where @input is used) or in a router-outlet substitution (where the router points directly to it. The exact same code will work for both situations. I use this pattern all the time.