Transferring data between two TypeScript files of different Angular 2 components

I have two components, Component A and Component B, which are not parent-child components but I need to pass data from Component A to Component B.

Example:
Component A.ts has an array of data:
myData: [
   {'name':'some a','email':'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630223040e020a0f4d000c0e">[email protected]</a>','grades':{}},
   {'name':'some b','email':'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e5c7b717d7570327f7371">[email protected]</a>','grades':{}}
]

I need to pass this myData to Component B.ts

Answer №1

If A and B do not have a parent/child relationship, the most effective approach is to utilize a shared service which is injected into their constructors.

component A:

constructor(private sharingService: SharingService) { }

public myArray = [];

func() {
    ...
    this.sharingService.save(this.myArray);
}

Service:

import { Injectable, } from '@angular/core';

@Injectable()
constructor() {}

private array = [];

save(array) {
    this.array = array;
}

fetch() {
    return this.array;
}

component B:

constructor(private sharingService: SharingService) { }

public yourArray = this.sharingService.fetch();

For further information on services and component interaction, refer to the Angular site tutorial.

Answer №2

My opinion aligns with the response from @Deceptive Dessert. Utilizing a service is crucial for facilitating data sharing between distinct components. The issue you're encountering with 'undefined' stems from invoking the fetch method within the constructor without specifying an initial value for the array, as demonstrated in: private array. To mitigate this, ensure that you either assign an initial value to the array or refrain from calling the fetch method until the array is no longer considered undefined.

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

Exploring Scroll Functionality for Inner Components Within Mat-tab

I am currently working on a small attendance project that involves using table components within mat-tab elements. However, I am facing an issue where the overflow from the table causes the entire component to scroll, when in fact I only want the table its ...

The argument supplied to the `openUri()` function should be in the form of a string, but instead, it is displaying as "undefined". Please ensure that the initial parameter provided to either `mongoose.connect()`

Encountered error: The `uri` parameter passed to `openUri()` must be a string, but it is currently set as "undefined". Please ensure that the first parameter in either `mongoose.connect()` or `mongoose.createConnection()` is a valid string. Below are the ...

Using React.js to Retrieve Data from the Server without AJAX Calls

Currently, I am in the process of creating a web application using Express.js for the back-end and React.js for the front-end. Prior to using React.js, I utilized EJS templating and followed a similar workflow on the back-end as shown below: var express = ...

Is it possible to navigate directly to a route using hashRouter instead of BrowserRouter after building a react app with webpack?

Issue Encountered Upon running npm run dev, the application loads successfully and I can navigate to the defined route "/", where the component is displayed. However, when using npm run buildDev and attempting to manually access "/login", it returns a "can ...

The Art of Angular Architecture: Transmitting Information from Parent to Child

Exploring the concept of templates within a template in the example below... @Component({ selector: 'component-a', template: `<div> <component-b></component-b> </div>` }) Should component-b share a s ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Discovering the specific type of an object property in TypeScript

I am currently working on implementing a lookup type within an object. Imagine my object structure as follows: class PersonList { persons = { john: 'description of john', bob: 'description of bob' } } I want to create a ge ...

Is there a way to avoid a child div overflowing its parent div when adjusting the CSS zoom property?

Is there a way to avoid overflow when changing CSS property using the zoom function? I've tried using overflow: scroll but it's not preventing overflow. let zoomInElem = document.getElementById('zoomIn') let zoomOutElem = document ...

Is there a way to verify the success of a Firebase push event upon submitting a form?

Here is the code for my polymer form and JavaScript. It works well in pushing data. What I would like to achieve is a way to verify if the push operation was successful or not. If it was successful, I want to hide the form and display a confirmation messag ...

Vuejs dropdown selections are not working as expected due to a bug

My dropdown menu is being populated with options based on an API response that looks like the following: {"value":"1371","label":"apple"},{"value":"1371","label":"banana"},{&qu ...

UI-Router is failing to transition states when $state.go() is called

I am currently troubleshooting a unit test for my user interface router routes, specifically focusing on the issue I encountered with the test not passing successfully. Within my test script, when checking the value of $state.current.name, it returns &apo ...

Is there a way to trigger the opening of a new file or page when a CSS animation comes to an end?

Is there a way to delay the loading of a function or page until after an animation has finished running in JavaScript, HTML, and CSS only? For instance, I'd like to run an animation first and then have a different website or content load afterwards fo ...

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

Guide to toggling the anchor tag functionality as a button with JavaScript

I am trying to dynamically enable or disable an anchor tag that is used as a button using JavaScript. Within a certain condition, I want to control the state of this button. Here is the specific button in question: <div class="row my-2 text-right& ...

Dynamically Updating Radio Button Status in Angular 7 Using Material Design

I am currently working on an Angular Material application that includes radio buttons. My goal is to update the selected button based on data retrieved from a database. While everything seems to be functioning properly, I have noticed that the checked butt ...

Set the mat-option as active by marking it with a check symbol

Currently, I am utilizing mat-autocomplete. Whenever a selection is made manually from the dropdown options, the chosen item is displayed with a distinct background color and has a checkmark on the right side. However, when an option in the dropdown is se ...

Get the unique _id value of the object once it has been added to an established collection

Recently, I encountered a mongodb document with the following schema: class: String, class_teacher: String, students: [ { student: String, marks: number } ] In this scenario, when adding a new student to the collection, each studen ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

What is the process for reinserting a list item into the nested elements?

Looking for help with manipulating a menu in HTML? I have a menu that I want to modify by removing and adding list items. While I've had success removing items, I'm struggling to properly use the add method. Here's an example of what my menu ...

Can a search engine algorithm be developed to display an iframe based on the keywords entered in the search query?

Is it possible to create a search engine algorithm in HTML, CSS, and JavaScript that takes keywords from a search bar input and displays the best solution (or solutions) through iframes? html, css, javascript Below is the code for the iframes and search ...