Reputation: 532
I am using rxjs BehaviorSubject to create a service, upon sending values from Component1 and on subscribing in Component3, I get the values in Component3, this is achieved
`import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserService {
constructor() { }
// Observable navItem source
public _navItemSource = new BehaviorSubject(undefined);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable();
// service command
changeNav(nu) {
this._navItemSource.next([...nu]);
}
}`
`this._userService.changeNav(self.notificationslist);`
`this.subscription = this._userService.navItem$.subscribe(item =>
this.item1 = item);`
Now I want to use the same service in one more component(Component2) to send some different values to the same component Component3
`this._userService.changeNav(this.updatedFlag);`
`this.subscription = this._userService.navItem$.subscribe(item =>
this.item1 = item);`
And then upon subscribing it on Component3 I should get all the values from Component1 and Component2. So I have updated my service file but I get the following error
caused by: this._navItemSource.asObservable(...).scan is not a function
Please correct me where I am going wrong as I am new to rxjs.
`import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserService {
constructor() {
}
// Observable navItem source
public _navItemSource = new BehaviorSubject(undefined);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable().scan((acc, one) =>(acc +
one));
// service command
changeNav(nu) {
this._navItemSource.next([...nu]);
}
}`
Upvotes: 1
Views: 1262
Reputation: 1083
make sure you import scan operator. and in the scan function to merge your results you can return a JSON with the previous and new value emitted
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import "rxjs/add/operator/scan";
@Injectable()
export class UserService {
constructor() {
}
// Observable navItem source
public _navItemSource = new BehaviorSubject(Object([]));
// Observable navItem stream
navItem$ = this._navItemSource.asObservable().scan((acc, one) => {
return {
'previous': acc, 'new': one
}
});
// service command
changeNav(nu) {
this._navItemSource.next([...nu]);
}
}
Upvotes: 1