Not able to get the data from shared service to component in angular 2

228 Views Asked by At

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?

0

There are 0 best solutions below