Sharing/passing data between two components

时间:2016-12-09 13:08:40

标签: angular

I have two components(each defined for a route). Inside one component(say component A), i have written a click event that makes a http call and provides a json. Here is my click event:

@Output() emitData = new EventEmitter();

constructor(private appService: AppService){
}

// click event 
getData() {    
  this.appService.getData();    
  this.emitData.emit(this.appService.getData());    
}

On the other component, i have written the following:

emitData(data: any){
   console.log("Data:",data);
}

Well i have seen the @Input() and @Output(), but here the @Output() is not providing me the expected output.(I think the reason could be that both components are at the same level).

Could someone please help me for the same.

1 个答案:

答案 0 :(得分:0)

您必须仅从getData函数发出数据,如下所示:

getData() {    
  this.appService.getData().subscribe((res) => {
    this.emitData.emit(res);    
  });
}