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?
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.
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.
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.
But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With