Skip to main content

Angular - 3 ways to pass data between two routes

Angular 14 (and older versions) provides several ways to pass data between two routes. Here are some of the common approaches: 
 

1. Query Parameters: You can pass data between two routes using query parameters. In the sending component, you can use the `Router` service to navigate to the receiving component and pass data in the query string. For example:
// Sending component
import { Router } from '@angular/router';

constructor(private router: Router) {}

onButtonClick() {
  let data = { id: 123, name: 'John' };
  this.router.navigate(['/receiving-component'], { queryParams: data });
}
In the receiving component, you can use the `ActivatedRoute` service to read the query parameters. For example:
// Receiving component
import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    console.log(params.id); // 123
    console.log(params.name); // 'John'
  });
}

2. Route Parameters:
You can also pass data between two routes using route parameters. In the sending component, you can use the `Router` service to navigate to the receiving component and pass data in the route parameters. For example:
// Sending component
import { Router } from '@angular/router';

constructor(private router: Router) {}

onButtonClick() {
  let data = { id: 123, name: 'John' };
  this.router.navigate(['/receiving-component', data.id]);
}

In the receiving component, you can use the `ActivatedRoute` service to read the route parameters. For example:
// Receiving component
import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params.subscribe(params => {
  console.log(params.id); // 123
  });
}

3. Shared Service:
You can also pass data between two routes using a shared service. In this approach, you create a service that can store data and inject it into both the sending and receiving components. For example:
// Shared service
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private data: any;

  setData(data: any) {
    this.data = data;
  }

  getData() {
    return this.data;
  }
}
In the sending component, you inject the shared service and call the `setData()` method to store data. For example:
// Sending component
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-sending',
  template: `<button(click)="onButtonClick()">Send Data</button>`
})

export class SendingComponent {

  constructor(private dataService: DataService) {}

  onButtonClick() {
    let data = { id: 123, name: 'John' };
    this.dataService.setData(data);
  }
}

In the receiving component, you inject the shared service and call the `getData()` method to retrieve data. For example:
// Receiving component
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-receiving',
  template: `
  {{ data?.id }}
  {{ data?.name }}`
})

export class ReceivingComponent {
  data: any;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.data = this.dataService.getData();
  }
}

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

Joe Rogan Solves Racism

Joe Rogan: Hey guys, welcome to the show. Today, we're gonna be talking about racism. It's a sensitive topic, but we're all here to have an honest conversation about it. Jordan Peterson: It's a complex issue, Joe. We should approach it with nuance and care. Ben Shapiro: Yeah, nuance and care are important, but let's also be honest about the facts. The left loves to cry racism at everything Joe Rogan: Ben, I think that's a little extreme. There's definitely still racism out there. Ben Shapiro: Of course there is, Joe. But we need to have an honest conversation about the root causes of racism. Jordan Peterson: And the role that culture and personal responsibility play in perpetuating it. Joe Rogan: Well, how do we solve racism then? Ben Shapiro: Easy. We just stop talking about it. Jordan Peterson: That's not a solution, Ben. We need to address the root causes. Joe Rogan: Yeah, but how do we do that? Ben Shapiro: We need to have a serious conversation...

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