How to create subject ( rx.js) with 2 parameters?

Max K picture Max K · Nov 25, 2016 · Viewed 10.3k times · Source

I am using service with subject as communication service for components in my angular2 application.

Calling method:

this.notification.create('test');

Service:

export class NotificationService {
  private static notificationSource = new Subject<any>()

  notiCreated$ = NotificationService.notificationSource.asObservable();

  create(message) {
    NotificationService.notificationSource.next(message);
  }
}

Called function:

  this.subscription = notification.notiCreated$.subscribe(
    data => {
       console.log(data);
       this.createNotification(data, 'warning');
  });

But I want to pass 2 params. And I got errors.

How can i do it?

Answer

eko picture eko · Nov 25, 2016

Since the api for next is next(value: T): void, it can only take one parameter. Ref: http://reactivex.io/rxjs/class/es6/Subscriber.js~Subscriber.html

As a workaround you can group the messages inside an object:

this.notification.create({message1:'test', message2:'test2'});

and when you consume, just select the message you need:

 this.subscription = notification.notiCreated$.subscribe(
    data => {
       console.log(data.message1, data.message2);
       this.createNotification(data.message1, 'warning');
  });