Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction:

A -> B -> C

To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code:

In Component C:

private _activatedRoute: ActivatedRoute,

ngOnInit(): void {
        let B_ID = this._activatedRoute.snapshot.queryParams['B_ID'];
}

However, if you want to retrieve data from Component A instead:

In Component C:

private _activatedRoute: ActivatedRoute,

ngOnInit(): void {
       // let A_ID = this._activatedRoute.parent.snapshot.queryParams['A_ID'];
//Failed to retrieve the A ID
}

Answer №1

When it comes to communication between components, using subjects can be a convenient solution.

For instance, if there are 3 components – A, B, and C – and you want to pass data from component A to component C, you need to create a service first.

Take the following example:

 export class DataTransferService {

  private messageSubject = new Subject<string>();
  Data$ = this.messageCommand.asObservable();

  sendMessage(msg: string) {
    this.messageSubject.next(msg);
  }
}

In this scenario, a string value `msg` is passed from component A to the service. The service utilizes a subject that is observable and emits the value to those who have subscribed to the method in the service as illustrated below.

import { Component, OnInit } from '@angular/core';
import { DataTransferService} from '../services/message.service';

@Component({
  selector: 'app-component-one',
  templateUrl: './component-one.component.html',
  styleUrls: ['./component-one.component.css']
})
export class AComponent implements OnInit {

  constructor(private DataService: DataTransferService) { }

  ngOnInit() {
  }
  const msg = "This is passed to the service";
  yourActionMethod() {
    this.DataService.sendMessage(msg);
  }
} 

Subsequently, we can subscribe to that service in component C so that the `msg` value is emitted.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataTransferService} from '../services/message.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.css']
})
export class CComponent implements OnInit, OnDestroy {

  messageSubscription: Subscription;
  message: string;

  constructor(private DataService: DataTransferService) { }

  ngOnInit() {
    this.subscribeToMessageEvents();
  }

  ngOnDestroy(): void {
    this.DataService.unsubscribe();
  }

  subscribeToMessageEvents() {
    this.messageSubscription = this.DataService.Data$.subscribe(
      (msg: string) => {
        this.message = msg;
      }
    );
  }

}

By following the code above, we can retrieve the `msg` value from AComponent using the `messageSubscription` in CComponent.

Answer №2

To retrieve the router data, you can use the router.events function and subscribe to it. Here is an example of how you can achieve this:

this.router.events.subscribe(value => {
    if (value instanceof RoutesRecognized) {
       console.log(value.state.root.queryParams);
       console.log(this.router.config);
    }
});

Explore the value Object to access values specific to a particular route.

Answer №3

My strategy involves creating a service to facilitate the sharing of information between components. Here's an example:

import { Injectable } from '@angular/core';
import {HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UtilsService {
  information:any;
.
.
.

By storing the information in the 'information' variable of the service before navigating away from component A, you can easily retrieve it in component C.

To make use of this functionality, remember to import the service and include it in your component's constructor.

import { UtilsService } from '../../providers/utils.service';

_

constructor(
    private utilsSvc: UtilsService,
  ) {

You can access the stored information using this.utilsSvc.information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JSON data in an ArrayBuffer with TypeScript

I am currently struggling with converting the received ArrayBuffer data from a server via Websocket into another format. Below is the WebSocket code snippet: let ws = new WebSocket('wss://api.example.com/websocket'); ws.binaryType = 'arrayb ...

Issue: Unable to load the file named 'script.ts' while employing chrome.scripting.executeScript

Currently, I am working on developing a chrome extension using Vite with React and Typescript along with CRXJS. This is my initial project in this domain. The issue I am encountering is related to executing a script on the current tab when a button is clic ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

The webpack-dev-server is missing the required module

Having trouble with starting my Angular project even after creating a new one using ng new AppName. When I run the project with ng serve, I still encounter an error that persists. Can someone help me resolve this issue? Error: Module not found - Error: Ca ...

Is it possible for an Angular App to function as an authenticated user for a real-time database?

Just a question, no code included. I want to restrict access to reading from RTDB only to authenticated users. However, I don't want every user to have to sign up individually. Instead, I would like to have one login tied to the angular app that auto ...

Angular 14 introduces a new feature that automatically joins open SVG paths when dynamically rendered from a data object

I developed an application to convert SVG code into a JSON object that can be stored in a database. Another app was created to dynamically display the rendered result on a webpage. The rendering output appears as shown in this image: Upon rendering, it se ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

Difficulty transferring information between two components by using services

I am trying to pass the values of an array from the Search component to the History component in order to display the search history. My current code structure looks like this: search-page.component.ts export class SearchPageComponent implements OnInit ...

Error encountered when upgrading to Material-UI v5 rc.0 with typescript

After updating my material-ui to version v5-rc.0, I decided to implement styled-components. However, as I was working on my Component.styles.ts file, I encountered an error: The inferred type of 'StyledStepper' cannot be named without a referen ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Images in Angular 2 not appearing until system reboot

When working with angular2 and nodejs to upload an image, I encounter an issue where after node uploads the file to the assets folder, an error occurs when attempting to display it in angular: GET http://localhost:4200/assets/img/3.jpg 404 (Not Found) In ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

Retrieve the specific object's methods based on a specified return type criteria

Initially, I have a class containing attributes and methods. My goal is to filter and retrieve only the keys of the methods. I created a utility type for this purpose and it worked smoothly: type FunctionPropertyNames<T> = { [K in keyof T]: T[K] e ...

Implement static backgrounds on images within an Angular application

I am new to using Angular 7 and I have hit a roadblock. I need help understanding how to resize images so that either the height is 270 and the width is less than 470, or the width is 470 and the height is less than 270. Once resized, I want to place these ...

Encountering a problem with the 'string' parameter when using TypeScript

I keep encountering the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ barkingRoadProject: string[]; }'. No index signature with a paramet ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

When attempting to compile Typescript code, error TS1128 occurs indicating a missing declaration or statement. However, the code functions correctly when executed through a server

Currently, I'm in the process of developing a project using Angular2. As part of this project, I have created a primary Component class which serves as a central piece: import { Component, OnInit} from '@angular/core'; import { submitServi ...

What steps are required to customize a pre-existing DevExtreme JQuery DataGrid that was initially built in a cshtml file using Typescript?

I'm currently developing a web application using DevExtreme JQuery. Within the frontend, I have set up a DataGrid in a cshtml file. With DevExtreme functionality, it's possible to include an Add Button to the DataGrid that triggers a popup for in ...