selenium 111 selenium 111 - 1 month ago 6
TypeScript Question

Can't communicate between components (Angular 2)

I have a scenario where I need to pass data between two components
Please find the below scenario of component tree.

A
/ \
B C
/ \ / \
D E F G


Here I need to pass data from G component to B component which are on same screen

Service

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

@Injectable()
export class myCommService {
private activeTabIndex = new Subject<number>();
public activeTabIndexs = new Subject<number>();
activeTab$ = this.activeTabIndex.asObservable();
selectedCount$=this.activeTabIndexs.asObservable();
constructor() { }
fnActiveTabIs(astronaut: number) {
debugger
this.activeTabIndex.next(astronaut);
}
fnSelected(astronauts: number) {
debugger
this.activeTabIndexs.next(astronauts);
}
}


G component:

import { Component, OnInit, Input } from '@angular/core';
import { myCommService} from '../../../../shared/services/comm.service';
@Component({
selector: 'app-bl-view-widget-menu',
templateUrl: './bl-view-widget-menu.component.html',
styleUrls: ['./bl-view-widget-menu.component.css'],
inputs: ['id'],
providers: [myCommService]
})
export class BlViewWidgetMenuComponent implements OnInit {

isToggle: boolean = true;
i = 1;
constructor(private myCommService: myCommService) { }
id: Number;
ngOnInit() {

}

fn(data, id) {
debugger
this.i = this.i + 1;
// alert(this.i);
this.myCommService.fnSelected(1);
}

}


B component:"

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { myCommService} from '../../shared/services/comm.service';

@Component({
// moduleId: module.id,
selector: 'app-bl-filter',
templateUrl: 'bl-filter.component.html',
styleUrls: ['bl-filter.component.css'],
providers: [myCommService]
})
export class BlFilterComponent implements OnInit {
showInfo: boolean = true;
activeTabIndex;
a;
constructor(
private myCommService: myCommService
) {
debugger
myCommService.selectedCount$.subscribe(
astronauts => {
this.a = astronauts;
});


}

ngOnInit() {
}


}


but here I was able to update date in service but in B component I wan't able to get that data from service.
There is no error, in fact I could not debug.
Any help would be appreciated.

Answer

It's because services are singleton per provider

Since you are injecting different instances of the service to both G and B components, you won't be able to archieve this.

You need to provide service in a common module like

@NgModule({
    imports: [],
    exports: [],
    declarations: [Gcomponent, BComponent], // <-- components declared in same module
    providers: [myCommService], // <--- service provided here
})