Max Karpovets Max Karpovets - 9 days ago 6
TypeScript Question

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

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

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');
  });
Comments