Discovering the best method to retrieve user details (email address) following a successful login across all pages or components within Angular

Discovering the world of Angular and TypeScript is quite exciting. In my Angular project, I have 8 pages that include a login and registration page. I'm facing an issue where I need to access the user's email data on every page/component but the traditional method of using emit function seems unreliable as the data gets lost upon page refresh. Can someone guide me towards a simple yet effective solution to retrieve the email id across all pages/components in my project?

Take a look at my login.ts file below:

        import { Component, OnInit } from '@angular/core';
        import { Router, ActivatedRoute } from '@angular/router'; 
        import { Input, Output, EventEmitter } from '@angular/core';
        import { FormGroup, FormControl } from '@angular/forms';
        import { DataService } from '../services/data.service'
        import {EventtosymptomsService } from '../services/eventtosymptoms.service';
        interface loginInfo
        {
          email: string;
          password: string;
        }
        interface Response{
          result: boolean;
        
        }
        @Component({
          selector: 'app-login',
          templateUrl: './login.component.html',
          styleUrls: ['./login.component.css']
        })
        export class LoginComponent implements OnInit {
          constructor(private router: Router, private route: ActivatedRoute, private dataService: DataService, private eventService: EventtosymptomsService ) { }
          isShown: boolean = true ; // default will be Patient Login
          
          PemailId:string = "";
          Ppassword:string = "";
          logininfo ={} as loginInfo;
          response = {} as Response;
          error_message:boolean = false;
          sendData:string;
          toggleShow() {
          console.log("In toggle show")
          this.isShown = ! this.isShown;
          this.error_message = false;
          }
         
      patientLogin(patient_emailid: string, patient_password: string)
      {
    
        this.logininfo.email = patient_emailid;
        this.logininfo.password = patient_password;
        console.log(this.logininfo)
        this.sendData = patient_emailid;
        this.loginCheckPatient()
        
      }
    
      Register()
      {
        console.log("hello")
        this.router.navigate(['register']);
    
      }
            loginCheckPatient() {
                this.dataService.loginCheck(this.logininfo)
                  .subscribe(data => {
                    console.log(data)
                    this.response = data;
                    if(this.response.result)
                  {
                    console.log("In response check", this.response["result"])
                    this.error_message = false
                    this.eventService.emit<{}>(this.sendData);
                    this.router.navigate(['analyseSymptoms']);
                  }
                  else{
                        console.log("In else")
                          this.error_message = true;
                  }
                  }
                  )
                  
              }
}
    

    

Below is my service code file (dataservice.ts)

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    import { ajax } from 'rxjs/ajax';
    
    @Injectable({
      providedIn: 'root'
    })
    export class DataService {
     
      loginPatient_url = "http://127.0.0.1:5000/api/loginPatient"

  constructor(private httpClient: HttpClient) { }
  loginCheck(person): Observable<any> {
    const headers = { 'content-type': 'application/json'}  
    const body=JSON.stringify(person);
    console.log(body)
    return this.httpClient.post(this.loginPatient_url , body,{'headers':headers})
  }
}

Answer №1

If you're looking to share data between components, consider using a BehaviorSubject. The BehaviorSubject stores the value that needs to be accessed by other components. Components can subscribe to this data and receive updates whenever the stored value changes. Here is a more in-depth explanation of how asObservable works. When calling updateDataSelection, we use the next method to update the BehaviorSubject with a new value. Start by creating a service like the one below:

`import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { loginInfo } from '../entities/data';

@Injectable()
export class DataService {

  private dataSource = new BehaviorSubject<loginInfo>(new loginInfo());
  data = this.dataSource.asObservable();

  constructor() { }

  updatedDataSelection(data: loginInfo){
    this.dataSource.next(data);
  }
  
}`

Include this service in all components where user details are needed.

`// Inject the service into the component

dataService.data.subscribe(data => {
  // Implement logic for when data changes
})

// Update the data value in the service
dataService.updateData(newData);

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

I encountered an issue with uploading an image file in Angular and am currently experiencing an error

media.components.html <div class="row justify-content-center" style="position:relative;top:105px;"> <div class="col-md-6"> <!-- form company info --> <div class="card card-outline-secondary"> <div ...

The installation process resulted in the failure of loading the Ionic plugin

After creating an app with Ionic, I encountered an error when installing a plugin core.js:1449 ERROR TypeError: Object(...) is not a function at AppRate.set [as preferences] (index.js:31) at MyApp.webpackJsonp.259.MyApp.initializeApp (app.componen ...

Setting up NextJs in Visual Studio Code with Yarn

When I used yarn create next-app --typescript to set up a TypeScript Next.js application with Yarn, everything seemed to be working fine with the command yarn run dev. However, Visual Studio Code was not recognizing any of the yarn packages that were added ...

Exploring the Relationship Between the ngOnInit and ionViewWillLoad Lifecycle Hooks

After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit and ionViewWillLoad. If my understanding serves me right, ngOnInit is an Angular lif ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...

Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list. List<PhonesContacts> phoneContacts = snapshot.data; Lis ...

Clearing error messages from a form using the reset button or after cancelling the form

I am having trouble removing the error outline around the input box and error messages displayed below it. When I cancel the form or click on the reset button, the input fields' content along with the error messages should be cleared. However, current ...

Executing an action in a child component when a button is clicked on the parent route

Currently, I am developing a web application using Angular 4 that involves both parent and child routes. Within the parent route, there are two buttons available - 'Add' and 'Remove'. I am seeking guidance on how to trigger a function ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

Struggling to make HttpClient Post work in Angular 5?

I'm facing an issue with my httpClient post request. The service is not throwing any errors, but it's also not successfully posting the data to the database. Below is the code snippet: dataService.ts import { Injectable } from '@angular/c ...

What different factors might lead to the triggering of a NavigationCancel event?

While observing router events in my Angular 2 application, I noticed a NavigationCancel event with reason: "". This led me to ponder on the various potential reasons that could cause a NavigationCancel event to be triggered, not only with an empty reason ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

having issues establishing a connection between Django and Angular 2

I'm facing an issue with connecting my Angular 2 app to Django because they are running on different servers. I tried using cors but it didn't work. Any suggestions for a simple way to make the connection between them? views.py # Home Page d ...

The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned. Ideally, I want the button to be automatically removed from the view once the object is ...

Concealing the Submit Button During Server Processing (Issues with Binding?)

My Angular 2 form is set up to send data to the server asynchronously. I want to provide users with visual feedback during the waiting period by changing the blue 'submit' button to a greyed-out 'Please wait...' button. To achieve this, ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

Formatting numbers in Angular 4 to display in Million or Thousand format

I need assistance with formatting numbers in my Angular 4 application. I want to display the number in a certain format based on its value. For example, if the number is 12.23 million, it should be displayed as 12.2M (with one decimal place). If the numbe ...