Adnan Yaseen
Adnan Yaseen

Reputation: 863

Sharing data between same level components

I have checked various question which involves passing data between parent/child and also between same level components through few other ways including shared service. I am trying to follow the Shared Service pattern to share the data. My simple Shared Service is as follow,

import {Component, Injectable} from '@angular/core'
import * as models from '../_models/models';

import { Subject }    from 'rxjs/Subject';


@Injectable()
export class SharedService {
    // Observable
  private detailSource = new Subject<models.Detail>();

  // Observable number streams
  detail$ = this.detailSource.asObservable();

  // Service commands
  setDetail(value: models.TaskInstance) {
     this.detailSource.next(value);
  }
}

In my Login component, I am calling an API for Login which returns an object,

login() {
    var task = this.api.getDetail().subscribe(
                (data) => this._detail = data,
                error =>{
                    console.log(error);
                },
                () => {
                    console.log("Detail retrieved successfully !");
                    this.sharedService.setDetail(this._detail);
                    this.router.navigate(['dashboard']); 
                }
    );
}

In the above login function inside my Login component, I am calling setTask from sharedService and setting the detail which is retrieved from API.

Now In the Dashboard component, I have the following code,

constructor(private sharedSrvice: SharedService) {
    this.tempVariable = sharedSrvice.detail$.subscribe(
        objDetail => {
            this._detail = objDetail;
        },
        error =>{
            console.log("Error: " + error)
        },
        () => {
            console.log("Shared Service completed !");
        }
    );
}

The issue is that nothing happens inside the constructor of dashboard. I am subscribing to the shared service inside the constructor of the dashboard but the none of the console.log I used are reached which means that this is not working. Maybe I have got this all wrong or doing something not correctly. I am not sure but do I need to use this SharedService in NgModule to be shared between components?

Upvotes: 0

Views: 2115

Answers (1)

Supamiu
Supamiu

Reputation: 8731

You should create a module that provides this service, it will be used to declare the fact that this service is provided across your module and only across this one.

Example:

@NgModule({
   imports:[...],//Probably HttpModule here, as you are calling an API
   ...
   providers:[SharedService]
})
export class FooModule{}

Then, in your AppModule, import this module

@NgModule({
   imports:[FooModule],
   ...
   providers:[]//Do not provide SharedService here, it's already in your FooModule.
})
export class AppModule{}

This will ensure you have one instance of SharedService in every components of your FooModule.

Upvotes: 1

Related Questions