2016-12-29 103 views
1

我有兩個組成部分,一個用的餐館列表,另一個與所選餐廳的菜單,拿到菜單我使用這項服務:角2服務不更新PARAMS

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')); 
    } 
} 

這是菜單組件,在那裏我稱之爲getRestaurantMenu()函數:

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); 
    }); 
    } 
} 

一切正常,我第一次選擇一家餐廳,以顯示它的菜單,但是當我回去,進入另一菜單getRestaurant服務是仍在使用我選擇的第一家餐廳的ID,我需要重新加載頁面以獲得正確的菜單,我知道問題出在服務上,因爲菜單組件中的餐廳對象具有更多信息,例如餐廳名稱,位置等信息正在顯示正確

我試圖解決它惠及ngZone,setTimeOut(),也調用餐館列表組件中的getRestaurantMenu,但問題始終相同,任何想法解決這個將不勝感激,謝謝

回答

1

你在覆蓋this.menuUrl在這一行this.menuUrl = this.menuUrl.replace(':id', restaurantId);在服務。

因此,下一次你調用服務getRestaurantMenu功能沒有什麼可更換和有效this.menuUrl變量仍然指向舊的標識。用const menuUrl = this.menuUrl.replace(':id', restaurantId);替換this.menuUrl = this.menuUrl.replace(':id', restaurantId);這樣你不會覆蓋服務屬性。您將使用本地函數變量。

+0

你說得對,我不敢相信我沒有看到,謝謝,這讓我瘋狂 –

+0

看着這個,我覺得像整個網址而不是整個網址,@AndrésChamorro應該只有基本路徑一個常量和服務中構建的菜單url。 – awm

+0

是的。這將是更清潔,無需使用替換。 – codeepic