angular 2 service is not updating params

2019-07-29 09:18发布

问题:

I have two components, one with a list of restaurants and another with the menu of the selected restaurant, to get the menu I use this service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http'
import {Observable} from 'rxjs/Rx'
import 'rxjs/add/operator/map'

import { RESTAURANT_MENU } from '../../_helpers/'

@Injectable()
export class RestaurantsService {

  private menuUrl = RESTAURANT_MENU

  constructor(private http: Http) { }

  getRestaurantMenu(restaurantId): Observable<void[]> {
    this.menuUrl = this.menuUrl.replace(':id', restaurantId);
    return this.http.get(this.menuUrl)
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
}

This is the menu component, where I call the getRestaurantMenu() function:

import { Component, OnInit } from '@angular/core';
import { RestaurantsService} from '../shared/restaurants.service';

@Component({
 selector: 'app-restaurant-menu',
 templateUrl: './restaurant-menu.component.html',
 styleUrls: ['./restaurant-menu.component.css']
})

export class RestaurantMenuComponent implements OnInit {

  constructor(private RestaurantsService: RestaurantsService) { }

  restaurant = JSON.parse(localStorage.getItem('currentMenu'))

  ngOnInit() {
    this.getRestaurantMenu(this.restaurant.id)
  }

  restaurantMenu: void[]

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

everything works fine the first time I select a restaurant to show its menu, but when I go back and get into another menu the getRestaurant service is still using the id of the very first restaurant I selected, I need to reload the page to get the right menu, I know that the problem is in the service because the restaurant object in the menu component has more info such as the restaurant name, the location etc. and that info is being displayed right

I've tried to solve it whit ngZone, setTimeOut(), and also calling the getRestaurantMenu from the restaurant list component but the problem its always the same, any idea to solve this would be appreciated, thanks

回答1:

You are overwriting this.menuUrl in this line this.menuUrl = this.menuUrl.replace(':id', restaurantId); in the service.

So next time you invoke the service getRestaurantMenu function there is nothing to replace and in effect this.menuUrlvariable still points to the old id. Replace this.menuUrl = this.menuUrl.replace(':id', restaurantId); with const menuUrl = this.menuUrl.replace(':id', restaurantId); That way you won't overwrite the service property. You will use local function variable instead.