Search code examples
angularrouterlink

binding data from get parameters angular router


how to get value from parameters in angular routerlink ??

this my code

Component.ts :

Hotels: struct_hotel;
id : struct_hotel['id'] 

constructor(
    private activatedRoute: ActivatedRoute,
    private _service: ResultService)
    {
      this.activatedRoute.queryParams.subscribe(params => {
          let id= params['id'];
          //console.log(id);  
      });
    }
getDetails(id): void {
    this._service.getHotel(this.id).then(Hotels => this.Hotels = Hotels);
}

ngOnInit():void {
    this.getDetails(this.id);
  }

Service :

private apidetail = 'http://localhost/bobobox/public/api/v1/room/show';
getHotel(id: string ): Promise<struct_hotel>
    {
        const url = `${this.apidetail}/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json() as struct_hotel[])
            .catch(this.handleError);
    }

and i call it on html like this {{Hotels.hotel_name}} and i got error ERROR TypeError: Cannot read property 'hotel_name' of undefined

can anyone help me ?


Solution

  • The problem you have here is due to the async call might not be ready before the ngOnInit runs.

    You need to put the this.getDetails(this.id); inside the subscribe in the constructor after reading the params

    this.activatedRoute.queryParams.subscribe(params => {
          let id= params['id'];
          this.getDetails(this.id);
      });
    

    Also there seems to be some inconsistency on the type of object you are trying to use and the one you are getting from the service.

    It seems you are passing an id to get one hotel so the response should be

    then(response => response.json() as struct_hotel)