Angular2:RxJS Subject not responding to events

2019-03-02 02:06发布

问题:

I maintain a table which is generated from array of objects in which on click on a row would give an object which contain data of that one particular row.I needed to share it with all other components no matter it is a parent,child or sibling and and hence i use Subject,similar to https://embed.plnkr.co/P8xCEwSKgcOg07pwDrlO/. The problem i face is, on click, I assume event isnot getting emitted due to which I see nothing being reflected in another component. PLease let me know where i went wrong and help resolving.My code is below:

patientlist.component.ts

 getPatientDetail(value)  { //value gets passed on click of row in table
        this.patientService.getPatientDetail(value);
   }

patient.service.ts

         patientdata=new Subject<Object>();
         currentdata=this.patientdata.asObservable();
          getPatientDetail(data:Object){
          console.log(data);
          this.patientdata.next(data);
          }

patient.component.ts

 constructor(private patientService: PatientService) {

   this.patientService.currentdata.subscribe(data=>{
    console.log("am here"); //even this doesn't get reflected
    this.data=data;
    console.log(this.data); //nothing here as well
    })};

回答1:

You need to declare provider of PatientService in PatientComponent, not in PatientList