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

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

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

Andrew Tate has a talk with Moist Cr1TiKaL

Moist: Hey guys, welcome back. Today, I have a special guest with me - the one and only Andrew Tate. Now, I know what you're thinking. Why? And also, isn't he in prison? We will get to that later. Anyway, what's going on, Tate? Andrew Tate: Hey, Moist, what's with your name? Sounds like you're a wet tissue or something. Moist: Well, Andrew, I could ask you the same thing. What's with your name? Sounds like a Victorian chimney sweep. Andrew Tate: My name is unique and distinguished. Moist: Unique, sure. But distinguished? I'm not so sure about that. It's more like you got it from a random name generator. Andrew Tate: That's not true. I come from a long line of Tates. Moist: And I come from a long line of moist things, like cake and towelettes. Andrew Tate: Very funny. You know, I don't understand why people find your videos so entertaining. Moist: Well, I don't understand why people find your tweets so enlightening. Andrew Tate: Hey now. My ...