Reddy
Reddy

Reputation: 21

Subscribe not being triggered when the subject values changes

I have two components A and B, and when an event occurs in A, I need to get the updated value in B in which I am subscribing to a service to get the latest value from A.

component A:

sendString(inputEntered){  //happens when on buttonclick
....
this.myService.sendRecent(inputEntered);
}

Service:

export class myService {
  private inputStringSource = new Subject<string>();
  public inputString$ = this.inputStringSource.asObservable();
  constructor() {}


  sendRecent(inputString: string) {
    this.inputStringSource.next(inputString);
  }

component B:

...

  ngOnInit(): void {

    this.myService.inputString$.subscribe(data => {
      console.log("input value ", data);
    });

Service is receiving new value but the subscription in component B is not being triggered.. what am I doing wrong here? Please let me know. Tried few option but still no luck.

Upvotes: 2

Views: 3417

Answers (3)

sachintiwari
sachintiwari

Reputation: 31

I think the problem might be with how you are importing service in your component. Now, since we don't have complete code reference, please make sure the module where you have put component B should not have service(myService in your example) in the providers list. BehaviourSubject subscribe works when the service is not explicitly mentioned in the providers of parent module.

Upvotes: 3

jagjeet
jagjeet

Reputation: 595

This may happen if you are sending data from component A before subscribing in component B you can try using ReplaySubject

private inputStringSource = new ReplaySubject<string>();

Upvotes: 4

Change this and try:

import { BehaviorSubject } from 'rxjs';

private inputStringSource = new BehaviorSubject<string>('');

If it doesn't works, try this change the service like this:

export class myService {

  private inputStringSource = new Subject<string>();

  public get inputString$() {
     return this.inputStringSource.asObservable();
  }
  
  constructor() {}


  sendRecent(inputString: string) {
    this.inputStringSource.next(inputString);
  }

Upvotes: 0

Related Questions