send data between components Angular 2

1

I'm using routerLink to send an id of a component with a list of restaurants to another component through the URL

[routerLink]="['../restaurant-menu', restaurant.id]"

in the other component I use it in the following way

ngOnInit() {
  this.restaurantId = this.router.snapshot.params['id']
  getRestaurantMenu(this.restaurantId)
}

restaurantMenu: void[]

getRestaurantMenu(id): void {
this.RestaurantsService.getRestaurantMenu(id)
    .subscribe(
        restaurantMenu => this.restaurantMenu = restaurantMenu,
        err => {
            console.log(err);
    });
}

Everything works correctly the first time I enter a restaurant, and it loads its menu, the problem is that when I return to the list of restaurants and enter a different one I am charged the menu of the first restaurant I enter, I have to refresh the page manually so that it loads the correct menu.

I do not know if the id is updated after calling the function of getRestaurantMenu () because no matter how many times I go out and enter different restaurants it will always be the menu of the first restaurant that I will also see if I do this :

<p> {{restaurantId}} </p>

The id number shown on the screen is correct. I have tried different ways to pass that id but the result is the same, what could be the problem? thanks

    
asked by Andrés Chamorro 05.12.2016 в 17:17
source

3 answers

1

If I'm not wrong, you have the problem in the subscription to the router service.

Before trying to explain the solution that I see, recommend that you read and look for information about the 'Observables' and the RxJs library, since the problem you pose is related to it.

I suppose that what you have called router will be of ActivatedRouter type and that you will have something of the style in the component's constructor:

 constructor(private route: ActivatedRoute,...){}

The ActivatedRoute service exposes the parameters of the current URL as 'Observable'. You can subscribe to this service in two ways, directly:

 //Cada valor emitido por el 'stream Observable' produce un nuevo valor  en la subscripción. 
 //Cada vez que el parametro 'id' cambien en la URL, se verá reflejado en la función subscribe:
 this.route.params.subscribe(...)

or through the snapshot, (your case):

//Al subscribirte al snapshot, únicamente, el primer valor que le llegue despúes de subscribir, 
//será el único que será reflejado en la función subscribe. 
//Aunque el valor del parametro 'id' cambie a lo largo del tiempo, dichos cambios 
//no se verán reflejados.

this.route.snapshot.params.subscribe(...)

This is the reason why, your code does not reflect the changes of the 'id' parameter.

To fix it:

ngOnInit() {
   this.route.params.switchMap(params:Params => this.RestaurantsService.getRestaurantMenu(params['id']))
        .subscribe(
            restaurantMenu => this.restaurantMenu = restaurantMenu,
            error => console.log(error)
   )      
}

In case you need to store the 'id' of the restaurant for other purposes, you could do it too:

  ngOnInit() {
   this.route.params.subscribe(
      params:Params => {
         this.restaurantId = params['id'];
         this.RestaurantsService.getRestaurantMenu(this.restaurantId))
           .subscribe(
              restaurantMenu => this.restaurantMenu = restaurantMenu,
              error => console.log(error)
   )      
}
    
answered by 06.12.2016 в 00:19
1

I think you need to use another hook, such as OnChanges , which is used as ngOnChanges() instead of ngOnInit() , since you might be loading several components into one module .ts or routing.ts . Remember that when you use ngOnInit() you load all the necessary once and you can not change that component, so it may load at the beginning empty and never wait to receive your restaurant.id .

    
answered by 22.03.2017 в 15:19
1

The problem is solved.

In summary, the service I used had a function that when inserting the first id stopped working because it tried to make a replace () of a part of the url that no longer existed when sending a second id, solve it by cleaning the data before redoing the replace ().

Thanks for the help and apologies again for the delay.

    
answered by 17.04.2017 в 17:57