2

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

1 Answers1

3

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();
  }
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • Brother its working fine. But brother i need to understand this thing can you tell me any link or resource where i can learn this thing. Or bro can you explain here in detail. thanks brother – Abdul Rehman Mar 22 '21 at 16:21
  • And brother can I have your linkedin Please i wana connect with you . – Abdul Rehman Mar 22 '21 at 16:23
  • @AbdulRehman: You could start here for resources: https://stackoverflow.com/q/43118769/6513921. LearnRxJS is also a good place to start. And while I'm pleased with request I don't unfortunately do LinkedIn at the moment. I'll update in the Stackoverflow Bio page if I ever get around to having one :) – ruth Mar 22 '21 at 16:38