角度2服务不更新参数

时间:2016-12-29 16:59:57

标签: angular angular2-services angular2-components

我有两个组件,一个包含餐馆列表,另一个包含所选餐厅的菜单,以获取我使用此服务的菜单:

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 个答案:

答案 0 :(得分:1)

您正在服务中的此行this.menuUrl覆盖this.menuUrl = this.menuUrl.replace(':id', restaurantId);

因此,下次调用服务getRestaurantMenu函数时,无需替换,实际上this.menuUrl变量仍指向旧ID。将this.menuUrl = this.menuUrl.replace(':id', restaurantId);替换为const menuUrl = this.menuUrl.replace(':id', restaurantId);这样您就不会覆盖服务属性。您将使用本地函数变量。