[Fixed] on First Click Rxjs not sending the value to other component in Angular

Issue

I am trying to send ProductId from one component to another component using Rxjs in Angular 2+. So When I click the event function for first time Rxjs sendFucntion did not send the ProductId to other component. But on 2nd click it does.

Here is the code

Rxjs Class for handling send and get calls
      
 import {Subject} from 'rxjs';

 @Injectable({
 providedIn: 'root'
 })

export class MessengerService {
_Subject = new Subject;
 constructor() { }

   SendMessageWithData(MessageAndData){
      this._Subject.next(MessageAndData);
   }

  GetMessageWithData(){
      return this._Subject.asObservable();
   }
}

Component 1.ts
      SendProductId(_ProductId){
         //Here I am getting the Product id here successfully I cheecked it using console.log
        this._MessengerService.SendMessageWithData(_ProductId);
        this._Router.navigate(['viewProduct']);
    }


  Component2.ts
  ngOnInit(): void {

     //Setting the Local Storage
     this._MessengerService.GetMessageWithData().subscribe(docs=>{
         console.log(docs);
         this._EcommerceDataService.SetLocalStorageForProductId(docs);
     });
 }

Now this is my logic with code. But its not working for first click on fucntion but worked after first click . Please guide me Regards

Solution

Most probably the first notification is emitted before the subscription. RxJS Subject will only emit the notifications to observers that are already subscribed to. You could instead use ReplaySubject with buffer 1.

import { ReplaySubject } from 'rxjs';

export class MessengerService {
  _Subject = new ReplaySubject(1);

  constructor() { }

  SendMessageWithData(MessageAndData){
    this._Subject.next(MessageAndData);
  }

  GetMessageWithData() {
    return this._Subject.asObservable();
  }
}

Leave a Reply

(*) Required, Your email will not be published