Skip to main content

Angular 14 - Using BehaviourSubject to pass data between routes

To pass data between two routes in Angular 14, you can use a combination of routing parameters and data services. Here's how:


1. Define a data service 

Create a service file that will be responsible for sharing data between components. Here's an example:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private messageSource = new BehaviorSubject("");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message);
  }
}
This service creates a `BehaviorSubject` that can be used to hold the data you want to pass between components. The `changeMessage` function can be used to update the value of the `BehaviorSubject`. 


2. Define a route with a parameter 

 In the `app-routing.module.ts` file, define a route that accepts a parameter. Here's an example:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Component1Component } from './component1/component1.component';
import { Component2Component } from './component2/component2.component';

const routes: Routes = [
  { path: '', redirectTo: '/component1', pathMatch: 'full' },
  { path: 'component1', component: Component1Component },
  { path: 'component2/:data', component: Component2Component }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

In this example, the `component2` route accepts a parameter called `data`


3. Update the data service 

 In the component that will pass the data, inject the data service and call the `changeMessage` function to update the `BehaviorSubject`. Here's an example:
import { Component } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-component1',
  template: `
<input type="text" [(ngModel)]="message">
<button (click)="sendMessage()">Send Message</button>
  `
})

export class Component1Component {
  message: string;

  constructor(private dataService: DataService) { }

  sendMessage() {
    this.dataService.changeMessage(this.message);
  }
}
In this example, the `Component1Component` sends a message by calling the `changeMessage` function of the `DataService`


4. Access the data in the receiving component 

 In the component that will receive the data, inject the data service and subscribe to the `currentMessage` observable. Here's an example:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-component2',
  template: `{{ message }}`
})

export class Component2Component implements OnInit {
  message: string;

  constructor(private dataService: DataService, private route: ActivatedRoute) { }

  ngOnInit() {

    this.route.params.subscribe(params => {
      this.message = params['data'];
    });

    this.dataService.currentMessage.subscribe(message => {
      this.message = message;
    });
  }
}
In this example, the `Component2Component` subscribes to both the `params` observable and the `currentMessage` observable. The `params` observable is used to get the value of the parameter `data` from the route, and the `currentMessage` observable is used to get the latest value of the `BehaviorSubject`.


That's it! With these steps, you can now pass data between two routes in Angular 14, or even older versions using a data service and routing parameters.

Comments

Popular posts from this blog

Andrew Tate meets The Joker

 Andrew Tate and Joker found themselves face-to-face, standing on opposite sides of a dimly lit alleyway.   Joker: "Well, well, well, who do we have here? It's Andrew Tate, the supposed expert in all things success and happiness. And yet, I see a man who is all bark and no bite." Andrew Tate: "Listen, clown. I don't have time for your childish games." The Joker: "Well, I heard some rumors that you've been in trouble with the law lately. Care to fill me in? Did you finally get caught for all those dirty little secrets you've been hiding?" Andrew Tate: (getting defensive) "I have no idea what you're talking about. I've never done anything illegal." The Joker: (laughing) "Oh, come on, Andrew. Don't be so uptight. I'm sure we've all done something we're not proud of." Andrew Tate: (sighing) "Fine, if you must know, I've been wrongly accused of something. But I'm fighting it in court a...

(Spanish) 8 Formas diferentes de ganar ingresos pasivos

Los ingresos pasivos se refieren al dinero ganado sin participación o esfuerzo activo. En lugar de intercambiar tiempo por dinero, los ingresos pasivos te permiten ganar dinero mientras duermes o te enfocas en otras actividades. A continuación, se presentan algunas formas diferentes de ganar ingresos pasivos: Propiedades de alquiler: Las propiedades de alquiler pueden ser una excelente fuente de ingresos pasivos. Una vez que compras una propiedad, puedes alquilarla y recibir pagos mensuales de alquiler. Con la administración adecuada de la propiedad, esto puede ser una fuente de ingresos sin tener que hacer mucho esfuerzo. Acciones de dividendos: Las acciones de dividendos son acciones que pagan dividendos de forma regular. Al invertir en acciones de dividendos, puedes recibir pagos regulares sin tener que vender tus acciones. Algunas compañías tienen una larga historia de pago de dividendos, y estas pueden ser fuentes confiables de ingresos pasivos. Préstamos entre particulares: Lo...

Yugi vs Kaiba - Deck List

Yugi's Deck   Monsters:   1x Dark Magician 1x Dark Magician Girl 1x Dark Magician of Chaos 1x King's Knight 1x Queen's Knight 1x Jack's Knight 1x Beta the Magnet Warrior 1x Gamma the Magnet Warrior 1x Alpha the Magnet Warrior 1x Valkyrion the Magna Warrior 1x Gazelle the King of Mythical Beasts 1x Berfomet 1x Blockman 1x Sangan 1x Watapon 1x Swift Gaia the Fierce Knight 1x Archfiend of Gilfer 1x Big Shield Gardna 1x Buster Blader 1x Black Luster Soldier 1x Black Luster Soldier - Envoy of the Beggining 1x Obelisk the Tormentor 1x The Winged Dragon of Ra 1x Slifer the Sky Dragon Spells:   1x Dark Magic Attack 1x Double Spell 1x Pot of Greed 1x Thousand Knives 1x Swords of Revealing Light 1x Graceful Charity 1x Monster Reborn 1x Dark Magic Curtain 1x Black Luster Ritual 1x Mystical Space Typhoon 1x Book of Moon 1x Dedication through Light and Darkness 1x One-Shot Wand 1x Polymerization Traps:   1x Mirror Force ...