Updating the navigation bar in Angular2 after routing in certain scenarios can be achieved by following these steps

I am working with a bootstrap navbar in my app, where I have links for login, logout, and register displayed on the right side of the navigation bar. This code snippet is from my app.component.html.ts file:

<div class="navbar-collapse collapse">
// Here i check if user is authenticated, display : Hello <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e8ebeac9eee4e8e0e5a7eae6e4">[email protected]</a>
<ul *ngIf="user" class="nav navbar-nav navbar-right">
          //code in here
</ul>
// If user is not authenticated, display Login - Register
<ul *ngIf="!user"  class="nav navbar-nav navbar-right">
  <li><a routerLink="/register" id="registerLink">Register</a></li>
  <li><a routerLink="/login" id="loginLink">Log in</a></li>
</ul>     

In my login.component.ts file, I utilize Authen.Service.ts to retrieve the token stored in localStorage:

import { UrlConstants } from './core/common/url.constants';
import { LoggedInUser } from './core/domain/loggedin.user';
import { SystemConstants } from './core/common/system.constants';


@Component({
  selector: 'app-login',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
    export class LoginComponent implements OnInit {
      public user: any;
      private isLoggedIn = false;


  loginUser(valid: boolean) {
    this.loading = true;
    if (valid) {
      const userData = {
        username: this.form.controls.username.value,
        password: this.form.controls.password.value
      }

      this._authenService.login(userData.username, userData.password).subscribe(data => {
        this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER));
        // If success redirect to Home view
        this._router.navigate([UrlConstants.HOME]);
      }, error => {
        this.loading = false;
      });

    }
  }  
  ngOnInit() {

  }

}

This is how my Authen.Service.ts looks like:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';

import { SystemConstants } from '../common/system.constants';
import { LoggedInUser } from '../domain/loggedin.user';


@Injectable()
export class AuthenService {

  constructor(private _http: Http) {
  }

  login(username: string, password: string) {
    let body = "userName=" + encodeURIComponent(username) +
      "&password=" + encodeURIComponent(password) +
      "&grant_type=password";
    let headers = new Headers();
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    let options = new RequestOptions({ headers: headers });

    return this._http.post(SystemConstants.BASE_API + '/api/oauth/token', body, options).map((response: Response) => {
      let user: LoggedInUser = response.json();
      if (user && user.access_token) {
        localStorage.removeItem(SystemConstants.CURRENT_USER);
        localStorage.setItem(SystemConstants.CURRENT_USER, JSON.stringify(user));
      }
    });
  }

  logout() {
    localStorage.removeItem(SystemConstants.CURRENT_USER);
  }

  isUserAuthenticated(): boolean {
    let user = localStorage.getItem(SystemConstants.CURRENT_USER);
    if (user != null) {
      return true;
    }
    else
      return false;
  }

Lastly, here is an excerpt from my app.component.ts:

    export class AppComponent implements OnInit {

    // the user object got from localStore 
    ngOnInit() {
        this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER));
        console.log(this.user);
      }
}

I am facing an issue where the navbar does not update its state immediately after authentication (despite having the token). I have to refresh the entire page to see the updated navbar content.

Any suggestions on how I can efficiently update the navigation bar in Angular without requiring a full page refresh? Thank you.

Answer â„–1

So, the issue you're facing is how to hide the "login" link on the main component after a user has successfully signed in.

One possible solution could be:

In your AuthService, introduce a public boolean property called "isLoggedIn":

@Injectable()
export class AuthService {
  isLoggedIn = false;
}

This AuthService can be shared among different components.

When a user successfully logs in, set the isLoggedIn property to true within the login component:

login(){
  this.auth.isLoggedIn = true
}

To handle the visibility of the "login" menu in the app component, subscribe to the NavigationEnd event of the router:

export class AppComponent {
  constructor(private router: Router, private auth:AuthService){}

  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event.constructor.name === "NavigationEnd") {
        this.isLoggedin = this.auth.isLoggedIn;
      }
    })
  }
}

Finally, in the app component template, control the display of the "login" menu using *ngIf="!isLoggedin"

You can also find a working example on Plunker. Hope this provides some guidance...

Answer â„–2

To ensure seamless communication of the user's authentication status, the AuthenService utilizes a BehaviorSubject. The AppComponent subscribes to this and updates the user variable accordingly, resulting in automatic updates to the navigation bar without requiring a page refresh.

  1. Begin by declaring a BehaviorSubject within the AuthenService:

    private userSubject = new BehaviorSubject<LoggedInUser>(null); user$: Observable<LoggedInUser> = this.userSubject.asObservable();

  2. In the login and logout methods, emit a new value for the userSubject:

    this.userSubject.next(user)

  3. Within the AppComponent, subscribe to the user$ observable and update the user variable:

    this.authenService.user$.subscribe(user => this.user = user)

Any changes to the user's login or logout status will automatically update the user variable in the AppComponent, leading to real-time updates in the navigation bar.

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

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: https://i.sstatic.net/ILdsl.png This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to id ...

Suggestions for specifying options with CapacitorSQLite.createSyncTable() when beginning to utilize @capacitor-community/sqlite

Currently, I am following a tutorial on capacitor ionic with sqlite from 2020. Unfortunately, there doesn't seem to be a more recent tutorial available online. (https://youtu.be/2kTT3k8ztL8?t=635) A lot has changed since the tutorial was released, bu ...

How to Retrieve Multiple Toggle Button Values using ID in AngularJS?

I am looking to retrieve the value of a toggle button as either yes or no. Since numerous questions are being generated dynamically, I need to determine this based on item.id. I am utilizing Angular and need to implement the logic in a TS file. Any assista ...

Guide to Setting Up CORS for Ajax POST Requests

I need help with setting up Cross-origin resource sharing (CORS) for an ajax POST request to a controller class on a different domain site in order to maintain session connectivity. I am currently using jQuery ajax call and have set the cross-domain proper ...

Having issues with Div CSS functionality not properly functioning

My background CSS is working fine, but the styling for the .about div is not applying. Here is my HTML code: <DOCTYPE! HTML> <head> <link rel="stylesheet" type="text/css" href="CSS.css"> </head> <body> ...

The design of the website is all over the place

I am encountering challenges in creating distinct containers for the header, body, and other sections of my website. The layout is not turning out as planned, and I can't pinpoint where my code is going wrong. Any advice or suggestions on how to resol ...

Issue regarding retrieving the image using TypeScript from an external API

Hey developers! I'm facing an issue with importing images from an external API. I used the tag: <img src = {photos [0] .src} /> but it doesn't seem to recognize the .src property. Can anyone shed some light on how this is supposed to work? ...

What causes sections that are the same to have varying heights?

My layout consists of 4 sections, each with an aside and main taking up half the screen. The first section's aside starts on the left, then moves to the right for the second, alternating each section. I have copied the HTML of the first section for th ...

Tips for altering text size within Angular Material form fields with floating placeholder

Looking to customize the font size of the placeholder text in an Angular Material form field? You can set two different font sizes: one for when the placeholder is normal and one for when it floats. Here's how you can achieve this: <mat-form-fiel ...

Stylish Responsive Design with HTML and CSS Centering

I am tasked with creating a landing page that features an image at the top with text, followed by a couple of videos and a 2-pixel strip line image that must stay at the bottom. <html> ... <body> <img src="topimage.png" alt="" /> <t ...

Binding two objects to a single event using Angular 2 syntax

Is there a way to connect two simple input fields to a single click event in Angular? One box for typing text and the other providing a timestamp from Date();. How can I show both values when clicking on the button? // The #date input field provides the ...

Utilize custom SMTP with JavaScript to dispatch emails

I'm wondering if it is possible to send emails using just JavaScript (I am working on a PhoneGap app). I envision a scenario where I can connect to a specific SMTP server with a login and password, and then send emails using that connection. I have al ...

Having issues with JQuery.Ajax() function, not entirely certain if the script is loading correctly

Attempting to utilize an API for sending emails through MailChimp without needing a backend. Unsure if Jquery script file is configured properly. $(document.ready(function () { $('#survey').click(function() { $.ajax({ type: “POSTâ ...

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

Bringing back a string from an external Ajax call

Learning something new can be challenging, so please bear with me: I've set out to create an image gallery that features a main index page where users can select various project categories, a sub-index page for selecting specific projects within the ...

Arrange the input fields on a single line in Rails for a clean and organized layout

Below is a Rails code snippet for input fields. Name:-<%=text_field_tag "specification[name1]","",:class=>"autocomplete form-control"%> <br/> Value:-<%=text_field_tag "specification[value1]","",:class=>"autocomplete form-control"%> ...

Learning to read HTML tags using JavaScript is a valuable skill

I've been struggling with a problem for some time now and I really need help fixing it. Here's the issue: I have an asp:GridView where I store text with HTML tags in my database under an English column. During the DataBound event, I use Context. ...

What is the process for javascript selecting a remote-data service?

I recently purchased a new app and am diving into Javascript and AngularJS for the first time. As I try to navigate through the code, I find myself puzzled by how the function in homeService.js is able to utilize remote-data.service.js. Featured below is ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

React: The error message is saying that it cannot retrieve the 'handler' property because it is either undefined or null

I'm having some trouble with event handlers in my React.js project. Every time I try to create an event handler outside of the render function, I end up with an error. Can anyone help me figure out what I'm doing wrong? class CheckboxHandler ext ...