0

In our Angular 2 project. I am trying to use shared services for communication between two components.

We've a BotData.SharedService.ts file like this:

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    import { Subject }    from 'rxjs/Subject';
    import { Observable } from 'rxjs/Observable';
    export interface Data {

        name: string,

    }

    @Injectable()
    export class BotDataService {
        sharingData: Observable<Data[]>

      private _sharingData: BehaviorSubject<Data[]>;

      private dataStore: {
        sharingData: Data[]
      };


      constructor() {
        this.dataStore = { sharingData: [] };
        this._sharingData = <BehaviorSubject<Data[]>>new BehaviorSubject([]);
      }

      saveData(userData) {
          console.log(userData)
         this._sharingData.next(userData); 
      }

      getData()  {
        console.log('get data function called' +  JSON.stringify( this.sharingData ) );
        return this._sharingData.asObservable();
      }
    }

Here, we're passing data using this._sharingData.next(userData); inside saveData(userData). Hence, this same data shall be available inside getData(). However, when we do console.log('get data function called' + JSON.stringify( this.sharingData ) this gives undefined.

Hence, botdataservice.getData() is breaking inside component:

   constructor(private botdataservice: BotDataService) {
        this.botdataservice = botdataservice;
        this.botdataservice.getData().subscribe(_sharingData => {
            //   this.userKonte = _sharingData;
              console.log(JSON.stringify(_sharingData));
          });
    }

What is the fix here?

smitesh
  • 1
  • 1
  • where is the definition of next function method ?? – Harrisss Jun 05 '17 at 07:39
  • The subject next method is used to send messages to an observable which are then sent to all subscribers of that observable. predefined function – smitesh Jun 05 '17 at 08:29
  • Can you share the definition of 'next' function ? – Harrisss Jun 05 '17 at 09:11
  • i have referred this http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject – smitesh Jun 05 '17 at 09:36
  • You are calling get function in subscription whereas calling next function in save method. I don't think this would work.As per blog next method of observable is applicable to all subscriptions of observer which is not so in your example – Harrisss Jun 05 '17 at 13:40

0 Answers0