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 Rick Sanchez

Rick Sanchez was walking through a multiverse portal when he suddenly bumped into Andrew Tate, a controversial internet personality.   Rick: "Oh, great. Just what I needed. Another internet troll from a universe I've never heard of." Andrew: "Excuse me? I demand respect. I'm a successful businessman and entrepreneur who has helped countless people achieve their goals." Rick: "Uh-huh. That's nice. But what have you really accomplished besides making money off of other people's insecurities?" Andrew: "I've achieved a lot. I've built a successful business and I'm a self-made millionaire." Rick: "Wow, a millionaire. That's so impressive. Maybe one day you'll be able to buy yourself some original thoughts."   Andrew: "What do you mean by that?" Rick: "I mean that you're just spouting the same tired cliches that every other self-help guru does. You don't have anything original or insi...

Joey vs Crow - Deck List

Video Joey's Deck  Monsters: 2x Red-Eyes Black Dragon 1x Alligator's Sword 1x Baby Dragon 1x Red-Eyes Darkness Metal Dragon 1x Red-Eyes Darkness Dragon 1x Gilford the Lightning 1x Gearfried the Iron Knight 1x Gearfried the Swordmaster 3x Swordsman of Landstar (not recommended) 1x Jinzo 1x Panther Warrior 1x Rocket Warrior 1x Little-Winguard 1x Time Wizard 1x Red-Eyes Black Chick 1x Copycat Spells: 1x Polymerization 1x Fusion Recovery 1x Silent Doom 1x Metamorphosis 1x Shield & Sword 1x Inferno Fire Blast 1x Release Restraint 1x Inferno Reckless Summon (not recommended) 1x Scapegoat 1x Graceful Dice 1x Megamorph 1x Salamandra 1x United We Stand Traps: 1x Mirror Force 1x Skull Dice 1x Raigeki Break 1x Nutrient Z 1x Kunai with Chain 1x Sakuretsu Armor 1x Remote Revenge 1x Graverobber 1x Magical Arm Shield 1x Call of the Haunted 1x Negate Attack Extra Deck: 1x Alligator...

Joe Rogan interviews Rick Sanchez

Joe: Welcome to the show, folks. Today, we have a very special guest. He's a mad scientist, a genius inventor, and a notorious alcoholic. Please welcome Rick Sanchez! Rick: (burps) Hey, what's up, Joe? It's good to be here, I guess. Joe: So, Rick, what's the secret to your success? How did you become such a renowned scientist? Rick: Well, Joe, let me tell you a little secret. I had an early life crisis and decided to drop out of high school to experiment with every drug known to man. After years of tripping balls, I stumbled upon a portal gun that opened my mind to a whole new universe of possibilities. Joe: That's insane, Rick. Speaking of drugs, have you ever tried DMT? Rick: DMT? Pfft, that's child's play. I've concocted a few of my own cocktails that make DMT look like Flintstone vitamins. Joe: (laughs) That's crazy. I gotta ask, have you ever experimented with any other kinds of drugs? Rick: (smirks) You know me too well, Joe. Let's just say...