Efficient methods to transfer values or arrays between components in Angular 8 without relying on local storage

I am working on a project that involves two components: a login component and a home component. I need to pass user data from the login component to the home component without using local storage. Is there a way to achieve this in Angular 8? Below is the code snippet for reference.

LoginComponent.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  users:any;
  constructor(private commonserviceService: CommonserviceService,private router: Router) { }

  ngOnInit() {
  this.users = [{"user1":"abc"},{"user2":"abcd"},{"user3":"abce"},{"user4":"abt"}];
  }
  storeData(){    
      this.router.navigate(['/home']);
  }

}

LoginComponent.html

<button (click)="storeData()">Go To Home Page</button>

HomeComponent.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor() { }

  ngOnInit() {

  }
}

Answer №1

There are various methods to accomplish this task depending on the specific use case. Typically, people opt for one of the following approaches:

1.) Establish a shared service that provides functions for storing and retrieving user data.

2.) Utilize a common parent component that maintains the state and passes it as @Input (https://angular.io/api/core/Input) to child components.

For more examples and scenarios, refer to the official documentation: https://angular.io/guide/component-interaction

Edit: Additionally, the solution offered by @Berchmans is accurate but involves sharing data between components within the same application using the HTTP Protocol. This may not be ideal for internal application communication.

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

Is it possible to define a variable within an array declaration?

I am trying to construct an array for the week, with each element being an instance of my "work hours" class. However, when attempting to define them within the array directly, I encounter an error. Upon inspecting the JS file, I noticed that the array is ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

Exploring the power of ContentChildren and ViewChildren in AngularElements with Angular 6 - a deep dive into

I have been experimenting with the new AngularElements feature which you can learn more about at https://angular.io/guide/elements. Initially, my tests were successful, but everything came to a halt when I integrated @ContentChildren. It makes sense to me ...

Invoke Observable.subscribe() sequentially

I have an array of objects and need to iterate over each element, making a request to the service for each one. However, I want to ensure that the next iteration only occurs when the current request is successfully completed, or block any further requests. ...

Misunderstanding the concept of always being right

Here is a code snippet that raises an error in TypeScript: class Status { constructor(public content: string){} } class Visitor { private status: Status | undefined = undefined; visit(tree: Tree) { if (tree.value > 7) { this.status = new ...

If an error 401 occurs, Angular 4 will redirect to the landing page

I am facing an issue with my Angular 4 app which has two modules: guest and user. When a user is not logged in and tries to navigate to .../user, it logs an error in the console. However, I am unable to locate the file responsible for handling this navigat ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

Is it true that one must have 280 different dependencies in order to use angular2?

Currently, I am following the ng2 getting started tutorial outlined here. It mainly involves working with a default package.json and running npm install. The package.json specifically lists two dev dependencies, while the rest are essential first or secon ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

Can a type be referenced using the generic name?

My selection includes: export type DocumentType = | Item | List | User export type DocumentInputType = | ItemInputType | ListInputType | UserInputType I want to develop a feature that can determine the input type based on the document type wi ...

Sending information to a service from the main.ts file in an Angular application

Within my Angular CLI application, I have a main.ts file that includes the following export statement. This file serves as a microservice that receives CONTEXT from another microservice. export default { async mount({ rootElement, context }: Extension) ...

I'm having trouble with TypeScript locating a method specified in a parent class's type definition. What might be causing this issue?

While working with JointJS, I came across the defined typings. In my Typescript class, the structure is as follows: namespace joint { namespace shapes { namespace devs { class Model extends basic.Generic { ... } } } } ...

Angular: utilizing two ngFors to target and update specific sections of the DOM

I'm facing a challenge and unsure if it's achievable in Angular. Below is a simple HTML code snippet: <div > <div *ngFor="let item of apiNames, let i = index" class="rescontainer"> <div class="resbox headline"> ...

Support for function calls is not available in Typescript version 2.1.5

I am encountering an issue with my ngrx reducer function: export const raceReducer: ActionReducer<IRace> = ( state: IRace = new Race(), action?: Action ) => { switch ( action.type ) { case RaceActions.ADD_OLP: return ngrxStateUpdater ...

Guide to waiting for API responses with redux-saga

I have a React-Typescript app with backend calls using React Saga. I'm facing an issue where when one of my frontend functions makes a backend call, the next function starts executing before the previous one finishes. Currently, I'm using the SE ...

The repository injected into NestJs using TypeORM suddenly becomes null

In my code, I am fetching Requisition data from an external system using the following approach: init() { const requisitionData = this.loginMb().pipe( map(response => response.data.token), switchMap(loginData => this.getRequisitions(loginD ...

Issue with NzPicker (nz-year-picker) due to absence of animation

Whenever I try to use the NzPicker, an error pops up on my screen. I'm encountering the same issue when adding the NzNoanimationModule. Is there a way to resolve this problem? <nz-year-picker (ngModelChange)="onChange($event)" nzPlaceHolder="sel ...

Nest is unable to resolve DataSource in the dependency injection

I've encountered an issue with dependencies while working on my NestJS project. When I try to launch the app, the compiler throws this error at me: [Nest] 16004 - 09.04.2022, 16:14:46 ERROR [ExceptionHandler] Nest can't resolve dependencies of ...

By default, Angular 6 now imports RxJS 6 operators seamlessly into its files

My Angular application extensively uses various RxJS 6 operators like filter, take, and takeUntil in almost all files. Importing these operators explicitly in every file is quite cumbersome. I wish there was a way to make them globally accessible. Imagine ...

What is the process for unsubscribing from a Firebase list in Angular2?

My code is set up to connect to a Firebase list by using the following: tasks: FirebaseListObservable<ITask[]>; constructor(private af: AngularFire) { this.tasks = this.af.database.list("/tasks"); } However, I am now facing an issue where I need ...