EventEmitter无法工作Angular 2

时间:2017-05-07 13:47:09

标签: angular eventemitter

我有一个餐馆列表,当点击其中一个时,我希望EventEmitter获取餐厅组件信息并提供详细信息组件。我正在尝试使用以下代码。当我运行getRestaurantDetails()时,控制台日志会打印出餐馆的名称,但我认为它可能没有发光或者能够订阅发射器。在details.ts中,第一个控制台日志被触发,第二个和第三个日志不被触发。请帮帮我。我一整天都想弄清楚。

restaurant.ts

import { Component, Input } from '@angular/core';
    import {Restaurant} from "./restaurant.model";
    import {RestaurantService} from "./restaurant.service";


    @Component({
      selector: 'app-restaurant',
      templateUrl: './restaurant.component.html',
      styleUrls: ['./restaurant.component.css']
    })
    export class RestaurantComponent {
      @Input() restaurant: Restaurant;


      constructor(private restaurantService: RestaurantService){

      }

      onSelect(){
        this.restaurantService.getRestaurantDetails(this.restaurant);
      }
    }

service.ts

import {Restaurant} from "./restaurant.model";
import {Http,Response } from "@angular/http";
import {Injectable,EventEmitter, Output} from "@angular/core"
import 'rxjs/Rx';
import {Observable} from "rxjs";

@Injectable()
export class RestaurantService{
    private restaurants: Restaurant[]=[];
    @Output() restaurantIsSelected = new EventEmitter<Restaurant>();

    constructor(private http: Http){

    }
getRestaurantDetails(restaurant: Restaurant){
        this.restaurantIsSelected.emit(restaurant);
        console.log(restaurant.name);
    }
    getRestaurantEmitter() {
        return this.restaurantIsSelected;
    }
}

details.ts

import { Component, OnInit } from '@angular/core';
import {Restaurant} from "./restaurant.model";
import {RestaurantService} from "./restaurant.service";

@Component({
  selector: 'app-restaurant-details',
  templateUrl: './restaurant-details.component.html',
  styleUrls: ['./restaurant-details.component.css']
})
export class RestaurantDetailsComponent implements OnInit{
  restaurant: Restaurant;

  constructor(private restaurantService: RestaurantService){}




  ngOnInit(){
    console.log("lol");

    this.restaurantService.getRestaurantEmitter().subscribe(
        (restaurant: Restaurant)=>{
      console.log(restaurant);
      console.log("lol");

      this.restaurant=restaurant;
    });
  }
}

0 个答案:

没有答案