0

I'm using Angular v2.1, I'm trying to make components send messages via a shared service.

I want firstly send data from the first component company.component.ts to the second component modal.component.ts.

I don't know exactly where's the problem (if it's while sending or receiving data). When I debug the receiving data, I found a Subscriber object:

Subscriber {closed: false, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: false…}

in the modal.service.ts :

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class ModalService {
  private sharedCompanySource = new Subject<string>();

  sharedCompany = this.sharedCompanySource.asObservable();

  getCompany(){
    return this.sharedCompany;
  }

  setCompany(_company: any){
    this.sharedCompanySource.next(_company);
  }
}

in the first component company.component.ts :

import { ModalService }  from './modals/modal.service';
@Component({
    templateUrl: 'company.component.html',
    providers: [
        ModalService
    ]
})
export class CompanyComponent implements OnInit {
  constructor(private missionService: ModalService) {
     this.missionService.setCompany("hellooooooooooooooo");
  }
}

in the second component modal.component.ts :

import { ModalService }  from './modals/modal.service';
import { Subscription }         from 'rxjs/Subscription';
@Component({
    templateUrl: 'modal.component.html',
    providers: [
        ModalService
    ]
})
export class ModalComponent implements OnInit {
  subscription:Subscription;
  constructor(private missionService: ModalService) {
     this.subscription = missionService.sharedCompany.subscribe();
  }
}
Mourad Idrissi
  • 3,455
  • 5
  • 17
  • 29

1 Answers1

3

Both components declare

providers: [
    ModalService
]

So they don't share the service. Both have their own separate instance of ModalService. That's what providers is for.

If you want a shared service, declare it in the providers of their parent NgModule.

Note that you also don't pass any callback to subscribe(), so nothing will happen avan when they start sharing the same service.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255