Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Communicating Between Sibling Components in Angular via a Service

Tech 1

1. Create a Shared Service

Create a shared service in a common directory using the CLI command: ng g s path/service-name, e.g., ng g s service/storage. This generates storage.service.ts with the following implementation:

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

@Injectable({
  providedIn: 'root'
})
export class StorageService {
  // Create a BehaviorSubject with an initial value of 0
  subject: BehaviorSubject<any> = new BehaviorSubject<any>(0);
}

2. Import and Register the Service in AppModule

In app.module.ts, import and regitser StorageService as a providre:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ComponentOneComponent } from './component-one/component-one.component';
import { ComponentTwoComponent } from './component-two/component-two.component';
import { StorageService } from './service/storage.service';

@NgModule({
  declarations: [
    AppComponent,
    ComponentOneComponent,
    ComponentTwoComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [StorageService],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. Component A (Sending Data)

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { StorageService } from '../service/storage.service';

@Component({
  selector: 'app-component-one',
  templateUrl: './component-one.component.html',
  styleUrls: ['./component-one.component.less']
})
export class ComponentOneComponent implements OnInit {
  inputValue = '';

  constructor(
    public storageService: StorageService,
    private router: Router
  ) { }

  ngOnInit(): void { }

  send(): void {
    this.router.navigate(['/two']);
    // Publish the input value via the shared service
    this.storageService.subject.next(this.inputValue);
  }
}

4. Component B (Receivnig Data)

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

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.less']
})
export class ComponentTwoComponent implements OnInit, OnDestroy {
  data: any;
  isVisible = false;
  private subscription: Subscription;

  constructor(public storageService: StorageService) {
    // Subscribe to the subject and capture the subscription
    this.subscription = this.storageService.subject.subscribe(value => {
      this.data = value;
      console.log('Data received');
    });
  }

  showData(): void {
    this.isVisible = true;
  }

  ngOnInit(): void { }

  ngOnDestroy(): void {
    // Unsubscribe to avoid memory leaks
    this.subscription.unsubscribe();
  }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.