-3

I have the following pubsub service:

export class PubSubService {
  subjects: Map<string, Subject<any>> = null;

  constructor() {
    this.subjects = new Map<string, Subject<any>>();
  }

  publish(data: { key: string, value: any }): void {
    let subject = this.subjects.get(data.key);
    if (!subject) {
      subject = new Subject<any>();
      this.subjects.set(data.key, subject);
    }
    subject.next(data.value);
  }

  subscribe(key: string): Observable<any> {
    let subject = this.subjects.get(key);
    if (!subject) {
      subject = new Subject<any>();
      this.subjects.set(key, subject);
    }
    return subject.asObservable();
  }
}

I'm publishing from AppComponent like this -

this.loggedInUser = 'John';
this. _pubSubService.publish({key:"loggedInUser", value:this.loggedInUser});

In the listening component I'm trying to subscribe to this service, but I'm not sure how I can convert Observable to String (in this case) or any custom object for that matter.

this._pubSubService.subscribe("loggedInUser"). ?? //not sure how to get the data here.

I'm new to rxjs concepts and so trying to use existing code snippets which is there in my project codebase and see if it makes any sense. Can you please guide me through what is the correct way of publishing and subscribing to an subject using pubsub model.

P.S - Earlier i was using a different approach and it worked fine - Angular 4 - rxjs BehaviorSubject usage in Service But then later i was asked to follow pubsub model which is more generic, hence trying the same.

Update 1 -

I just noticed typo in my question, sorry for that. I'm subscribing like this-

this._pubSubService.subscribe("loggedInUser").subscribe(...). //What should I be doing here, should I use Map? 

I tried following -

this.subscription = this._pubSubService.subscribe("loggedInUser").subscribe(data=>{this.loggedInUser=data});
console.log('this.user::'+this.loggedInUser);//Prints 'undefined'.
Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
coder87
  • 145
  • 1
  • 8
  • 21

1 Answers1

0

The problem is that you mix sync and async code. When you log the loggedInUser it has not been set yet:

this.subscription = this._pubSubService.subscribe("loggedInUser").subscribe(data=>{
  //this code runs asynchronous
  this.loggedInUser=data
});
//the following code runs directly after the subscribe synchronous
console.log('this.user::'+this.loggedInUser);//Prints 'undefined'.

If you would set the loggedInUser and log it from the subscribe then you would have data.

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57