Load the data of the app component in Angular 2 once a user has successfully logged in on a different

I am having an issue with my app.component where the user's email is not showing in the top menu immediately after logging in and being redirected to the data list page. The email only appears after I reload the page.

What I need is for the email to display right after the user logs in and is redirected to the data list page.

Below is the code snippet from app.component:

export class AppComponent implements OnInit{
  title = 'app works!';
  userEmail: any;
  constructor(private authService: AuthService, private router: Router) { }

  ngOnInit() {
    this.userEmail = this.authService.getUser().name;
    console.log(this.userEmail);
  }
}

And here is a snippet from the login component:

onLogin(){
    const user ={
      email: this.email,
      password: this.password
    }

    this.authService.loginUser(user).subscribe((data)=>{
      if(data.success){
        this.authService.userData(data.token, data.user);
        this.flashMessage.show('You are logged in.', {cssClass: 'alert-success'});
        this.router.navigate(['/']);
      }else{
        console.log('user didn\'t logged in');
        this.flashMessage.show('You are not logged in. Wrong email or password.', {cssClass: 'alert-danger', timeout: 2000})
        this.router.navigate(['/login']);
      }
    });

  }

Answer №1

To ensure seamless communication between components, consider making the user an observable within the login service. By having the AppComponent subscribe to this observable, you can easily retrieve necessary data once a successful login occurs. This approach allows for efficient synchronization of values. Does this logic resonate with you?

For a detailed illustration, refer to the Angular documentation where parent and children components communicate via a shared service: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

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

What steps can I take to make my search button work with this JavaScript code?

I am struggling with integrating my custom search bar with a JavaScript code to make it functional. Here is the code snippet for the Search Button: document.getElementById('searchform').onsubmit = function() { window.location = 'http:/ ...

Having trouble with Rollup resolving my typings file during the build process

Embarking on the journey of creating my inaugural library, I diligently followed a comprehensive guide. Utilizing rollup to consolidate all components and dependencies. The conundrum that currently besets me is the perplexing error thrown by rollup regard ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

NodeJS Multer for handling multiple form fields

Dealing with Multer for multiple fields can be a challenge. I am in need of uploading images using the file field for one image, as well as utilizing "Summernote" to upload another image. All of this needs to be handled within one controller. How should ...

What is the most effective method for organizing nested views?

I am seeking guidance on the recommended approach for nesting Backbone Views. Here are some possible methods for nesting views: Rendering all views and assembling them in the Router Having an IndexView handle all nesting, which is then called in the rou ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

The issue of Angular2 routing failing to function properly arises after deploying the 'dist' folder onto a Tom

After successfully generating the dist folder in my project prj-routing-final using angular-cli with the command ng-build --prod --aot, I deployed it onto a tomcat server. Everything seemed to be working fine as I was able to navigate to all routes at http ...

Use the $.get() method in JavaScript to send a parameter to my controller function

My objective is to showcase the event details in a modal. To achieve this, I am running a JavaScript script that calls the "GetEventsDetails" method in my "Event" controller with the event ID. While debugging in Chrome, I can see the ID being passed corre ...

Optimizing Content Responsiveness with Bootstrap in Offcanvas Sidebar Layouts

Here is an example of my current working code: Fiddle. This is what I want to achieve: The content within the <section> (such as the three circles) is designed to be responsive and adjust itself according to the browser size. If you resize the Fid ...

What's the best way to display alerts for a bad request and automatically redirect on successful submissions?

I am currently working on a registration form where the user gets redirected to home.php after successful submission, which is working fine. However, I am facing an issue where all alerts and errors echoed in PHP are redirecting to register.php and showin ...

How can one access the property "this.var" within a function declared within an object

I stumbled upon this snippet of code var person = { name: "joseph", age: 33, favSong: function killingInTheTameOf(){ this.lyrics = "Those who died are justified"; } }; document.write(person.lyrics); //doesn't work My curiosi ...

Saving received JSON data from fetch() API request into a variable

Just starting out with JS and currently working on a project involving retrieving data from an API using a JS Notebook. I'm trying to create a function that can make API calls based on a given URL, and then execute that function twice. The objective ...

Guide to successfully implement a POST action using jquery/ajax Colorbox! Check out the demo here

I stumbled upon a colorbox tutorial and attempted to replicate it with a POST action, but unfortunately, it just continues to load. Check out this fiddle The button represents the problematic POST action, while the text link is the original example that ...

Choosing an element beneath a table row using a different element as a reference

I'm attempting to identify the checkboxes associated with the link containing delete.jpg. Here's what I've tried so far: <table> <tr class="odd"> <td><input id="cbox1" type="checkbox"></input></td> ...

Incorporate an onclick function into the text tag element

When working with HTML, I often use text tags like this: <text id="aaa" > text</text> I'm curious if it's possible to add an onclick event to this? I attempted the following: var a = document.getElementById('aaa'); a.el ...

Implement the conversion of a response to the JSON response standard within a NestJS application

I encountered an issue with converting the output of my object post saving it in the database. I attempted to adhere to the guidelines laid out by and convert my responses to the Json standard. The approach I took is not optimal. Here it is: async find ...

Failure to choose a value in AngularJS using the Chosen directive

I am currently developing a project with AngularJS and I need to display the selected value. To achieve this, I am utilizing the chosen filter available at: https://github.com/leocaseiro/angular-chosen Below is the code snippet that I have implemented: ...

"Experience a refreshing twist on Material Design Color Utilities when paired with Material Web Components for surprising

I have been working on a project where I am utilizing the Material Design Color Utilities package to generate a dynamic color theme based on a primary color. However, I have encountered an issue where the generated colors are not matching my expectations. ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...