Enthu
Enthu

Reputation: 532

To merge values from different sources in my rxjs BehaviorSubject

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

Service file

`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]);
     }
  }`

Component1

  `this._userService.changeNav(self.notificationslist);`

Component3

  `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

Component2

 `this._userService.changeNav(this.updatedFlag);`

Component3

  `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.

Updated Service file

`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

Answers (1)

JayDeeEss
JayDeeEss

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

Working Plunker

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

Related Questions