Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data sharing between components in Angular 6

I have created 2 components and one service as below,

component-interaction.service.ts

@Injectable()
export class ComponentInteractionService {

  public dataSubject = new BehaviorSubject<string>("Test");

  getTestData(): Observable<any> {
    return this.dataSubject.asObservable();
  }

  pustTestData(dataToPush: string): void {
    this.dataSubject.next(dataToPush);
  }
}

first.component.ts

export class FirstComponent {

  constructor(private componentInteractionService: ComponentInteractionService) { 
    componentInteractionService.getTestData().subscribe(data=> {
      console.log("Received at 1 -- " + data);
    });
  }

  sendTestData(): void {
    this.componentInteractionService.pustTestData("sending data from 1");
  }

}

second.component.ts

export class SecondComponent {

  constructor(private componentInteractionService: ComponentInteractionService) { 
    componentInteractionService.getTestData().subscribe(data=> {
      console.log("Received at 2 -- " + data);
    });
  }
}

The issue I am currently facing is

On page load both the components subscribers are being triggered, but when I push data using sendTestData() method in FirstComponent, only the subscriber in FirstComponent is being triggered. The subscriber in SecondComponent is not being triggered. What should I do for both subscribers to get triggered on pushing data using the sendTestData() method?

My Console logs are as below..

Received at 1 -- Test

Received at 2 -- Test

Received at 1 -- sending data from 1

Expected Output..

Received at 1 -- Test

Received at 2 -- Test

Received at 1 -- sending data from 1

Received at 2 -- sending data from 1

like image 425
Santhosh mp Avatar asked Jun 13 '26 12:06

Santhosh mp


1 Answers

It is because you provide the same service twice in both AppComponentOne and AppComponentTwo so they both have different instances of the same service.

Empty providers array of both component and provide the service within app.module.ts

@Component({
  selector: 'app-distinct-first-component',
  template: '<button (click)="sendTestData()">Click to send Data</button>',
  providers: [ComponentService] // <= remove this line from both components
})

app.module.ts

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, 
  FirstComponent, SecondComponent
  ],
  bootstrap:    [ AppComponent ],
  providers: [ComponentService] // <= provide it here
})
export class AppModule { }
like image 73
Bunyamin Coskuner Avatar answered Jun 15 '26 04:06

Bunyamin Coskuner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!