Loading...

Non-Related Component Communication

In Angular, communicating between components that don't have a direct parent-child relationship requires a different approach. We'll explore how to use a shared service and Subject/Observable to achieve this.

Using a Shared Service and Subject/Observable

The most common and recommended way to facilitate communication between non-related components is by using a shared service. This service acts as a central point for data exchange.

Step 1: Create a Shared Service

Create a service named data.service.ts.

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

    @Injectable({
      providedIn: 'root'
    })
    export class DataService {
      private messageSource = new Subject<string>();
      message$ = this.messageSource.asObservable();

      sendMessage(message: string) {
        this.messageSource.next(message);
      }
    }
    

Explanation:

  • @Injectable({ providedIn: 'root' }): Makes the service available throughout the application.
  • private messageSource = new Subject<string>();: Creates a Subject, which is both an Observable and an Observer.
  • message$ = this.messageSource.asObservable();: Exposes the Subject as an Observable.
  • sendMessage(message: string): Sends a message to all subscribers.

Step 2: Component 1 (Sender)

Create a component that sends a message.


    import { Component } from '@angular/core';
    import { DataService } from './data.service';

    @Component({
      selector: 'app-component1',
      template: `
        <button (click)="sendMessage()">Send Message</button>
      `
    })
    export class Component1Component {
      constructor(private dataService: DataService) {}

      sendMessage() {
        this.dataService.sendMessage('Hello from Component 1!');
      }
    }
    

Step 3: Component 2 (Receiver)

Create a component that receives the message.


    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { DataService } from './data.service';
    import { Subscription } from 'rxjs';

    @Component({
      selector: 'app-component2',
      template: `
        <p>Received Message: {{ receivedMessage }}</p>
      `
    })
    export class Component2Component implements OnInit, OnDestroy {
      receivedMessage: string = '';
      private subscription: Subscription;

      constructor(private dataService: DataService) {}

      ngOnInit() {
        this.subscription = this.dataService.message$.subscribe(message => {
          this.receivedMessage = message;
        });
      }

      ngOnDestroy() {
        if (this.subscription) {
          this.subscription.unsubscribe();
        }
      }
    }
    

Explanation:

  • ngOnInit(): Subscribes to the message$ Observable and updates receivedMessage when a new message arrives.
  • ngOnDestroy(): Unsubscribes from the Observable to prevent memory leaks.

Key Points

  • A shared service acts as a central communication point.
  • Subject is used to create an Observable that can emit values.
  • Components subscribe to the Observable to receive messages.
  • Unsubscribing from the Observable in ngOnDestroy() is crucial to prevent memory leaks.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!