简体   繁体   中英

Communication between non related components with EventEmitter

The EventEmitter is not working and I dont get any errors so I do not know where the problem is.

My Service:

public newRecommendEmitter:EventEmitter<any> = new EventEmitter<any>();

addNewRecommendation(purchaseRecommend):Observable<any>{ 
  debugger;
  let url = this.baseUrl + "component/newPurchaseRecommend";
  return this.http.post(url, JSON.stringify(purchaseRecommend), this.options).pipe(map((data)=>{
    this.newRecommendEmitter.emit(data); // This is where I emit the new Data.
  }))
 
}

My First Component which send the data:

sendRecommandation() {

  this.recommandPurchase.user = this.authService.loggedInUser.userName;

  // here is where I send the data to the service , I emit the new data in that service as you can see above.
  this.inventoryService.addNewRecommendation(this.recommandPurchase).subscribe(data => {
    if (data) {
      this.toastSrv.success("New Recommendation Added")

    }
  })   

}

My Second Component which should get the data:

 ngOnInit() {

   this.inventoryService.newRecommendEmitter.subscribe(data=>{
     debugger;
      this.purchaseRecommendations.push(data)
    })
  }

Any idea where I went wrong?

EventEmitter is an Angular specific extension of RxJS Subject multicast observable. Subject s will only emit the notifications that were emitted after the subscription. In your case probably the emission is before the subscription.

You could look into RxJS ReplaySubject with buffer 1 instead. It will buffer the latest emission and emit it to future observers immediately upon subscription.

Moreover the RxJS map operator is used to transform the emitted value from the observable. You could use tap instead to perform side-effects.

Try the following

public newRecommendEmitter: ReplaySubject<any> = new ReplaySubject<any>(1);

addNewRecommendation(purchaseRecommend):Observable<any>{ 
  debugger;
  let url = this.baseUrl + "component/newPurchaseRecommend";
  return this.http.post(url, JSON.stringify(purchaseRecommend), this.options).pipe(
    tap((data) => {
      this.newRecommendEmitter.next(data); // Use `next` here
    })
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM