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

(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...

Yusei vs Zane - Deck List

Video Yusei's Deck Monsters: 3x Junk Synchron 3x Quillbolt Hedgehog 3x Tuningware 2x Doppelwarrior 1x Quickdraw Synchron 1x Bri Synchron 1x Debris Dragon 1x Drill Synchron 3x Level Warrior 1x Fortress Warrior 1x Necro Linker 1x Nitro Synchron 1x Shield Wing 1x Synchron Explorer 1x Level Eater 1x Sonic Chick 1x Turbo Synchron 1x Swift Scarecrow 1x Mach Synchron Spells: 2x Stardust Shimmer 2x Tuning 1x One for One 1x Falling Current 1x Resonance Device 1x Machine Duplication 1x Book of Moon 1x Megamorph Traps: 2x Defense Draw 1x Spirit Force 1x Miracle's Wake 1x Synchro Deflector 1x Give and Take 1x Hope for Escape 1x Miracle Locus 1x Scrap-Iron Scarecrow 1x Limit Reversse 1x Call of the Haunted 1x Graceful Revival 1x Gathering Wishes 1x Cursed Prison Extra Deck: 2x Junk Warrior 1x Shooting Quasar Dragon 1x Shooting Star Dragon 1x Stardust Dragon 1x Formula Synchron 1x Re...

Rogan, Musk and Snoop

Joe: Hey guys, welcome to the show! Today we have Elon Musk and Snoop Dog joining us today. What's up? Elon: Not much, Joe. Just busy launching rockets and trying to colonize Mars. Snoop: And I'm just chillin', smokin' some weed, you know. Joe Rogan: So, Elon, you're known for pushing the limits of technology and innovation. What's the next big thing we can expect from you? Elon Musk: Well, Joe, we're working on a new project that will revolutionize the way we travel. We're creating a system of underground tunnels that will allow people to travel across cities at high speed. Joe Rogan: Oh, that's cool! But what if people get bored in the tunnels? Shouldn't you add some kind of entertainment? Snoop: Yeah, like strippers and pole dancing! Elon Musk: Well, that's an interesting idea, Snoop. But I think we'll stick to something a bit more practical. Joe Rogan: And what about colonizing Mars? What's the plan? Elon Musk: Well, Joe, it...