Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
Max K Avatar asked Nov 25 '16 12:11

Max K


People also ask

What is the difference between BehaviorSubject and subject?

A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.

What is the difference between an observable and a subject?

The main difference between an Observable and a Subject is that a plain Observable by default is unicast. It means that each subscribed Observer owns an independent execution of the Observable. On the other hand, Subjects are multicast. A Subject is like an Observable, but it can multicast to many Observers.

Why use subject instead of observable?

In comparison to a regular Observable, a Subject allows values to be multicasted to many Observers. A Subject and its subscribers have a one-to-many relationship. A Subject can be an Observable as well as an Observer. They hold a registry of many listeners to multiple Observables.

What are different types of subject in RxJS?

But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.


1 Answers

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');
  });
like image 75
eko Avatar answered Sep 21 '22 19:09

eko