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

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

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

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