Refreshing Angular navigation directive post user authentication

As I delve into mastering AngularJS and embark on my inaugural "real" project, I find myself at a crossroads. Despite hours of scouring the internet in search of answers, I have yet to stumble upon a suitable solution that speaks to me in layman's terms.

In this project, I’ve designed a directive solely responsible for rendering a navigation header:

app.directive('navDirective', function() {
    return {
              templateUrl: '../../views/nav.html'
           };
});

Within my index.html file lies this simple declaration:

<nav-directive> </nav-directive>

Initially, I smoothly integrated Auth0 functionality, which gracefully displayed specific navigational elements based on user authentication status. However, as I transition from using Auth0 to local authentication via Passport’s local strategy, I encounter a hitch - the navigation template fails to update promptly post-login unless I manually refresh the browser.

I suspect this anomaly stems from Auth0 redirecting users momentarily outside the website, triggering a callback to reload the page and reflect the updated nav items.

Now, with local login through Passport, how can I trigger a dynamic reload of the navigation template or alter the visibility of list items based on user authentication?

After delving into discussions, I stumbled upon suggestions involving $watch for achieving this behavior. Sadly, while I understand the concept, I remain befuddled by its implementation within the link function and the mechanism to activate it.

The structure of my nav.html template is as follows:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark" ng-controller="NavCtrl">
        <a class="navbar-brand" href="#" ng-show="currentUser">User: {{ currentUser.username }}</a>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse navbarCollapse justify-content-end" id="navbarNavDropdown">
          <ul class="nav navbar-nav ">  

            <li class="nav-item" ng-show="currentUser">
              <a class="nav-link nav-item-colapse" ui-sref="home">Home </a>
            </li>

            <li class="nav-item" ng-show="currentUser">
              <a class="nav-link nav-item-colapse" ui-sref="view2">View 2</a>
            </li>

            <li class="nav-item" ng-show="currentUser">
              <a class="nav-link nav-item-colapse" ui-sref="view3">View 3</a>
            </li> 

            <li class="nav-item" ng-show="currentUser">
                <a class="nav-link nav-item-colapse" ui-sref="reports">Reports</a>
            </li>


            <li class="nav-item dropdown" ng-show="currentUser">
              <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Admin
              </a>
              <div class="dropdown-menu" style="right: 0; left: auto;" aria-labelledby="navbarDropdownMenuLink">
                <a class="dropdown-item nav-item-colapse" ui-sref="sub1">Sub Task1</a>
                <a class="dropdown-item nav-item-colapse" ui-sref="sub2">Sub Task2</a>
                <a class="dropdown-item nav-item-colapse" href="http://www.google.com">Do Something Else</a>
              </div>
            </li>

            <li class="nav-item">
              <a class="nav-link active" ui-sref="login" ng-show="!currentUser">Login</a>
          </li>


            <li class="nav-item">
                <a class="nav-link" ng-click="logout()" ng-show="currentUser">Logout</a>
            </li>

          </ul>
        </div>
      </nav>

Meanwhile, my navCtrl stands firm:

app.controller("navCtrl", function($scope, mainSrvc) {

    mainSrvc.getUser().then(function(user){
      $scope.user = (user.data);
      console.log('nav ctrl ran')  // except it doesn't when logging in locally
      console.log(($scope.user));
    });
  });

At this juncture, uncertainty looms over my approach. Any insights or guidance would be immensely appreciated!

Answer №1

To determine whether a user is currently logged in, you can utilize the ng-if="vm.isLoggedIn()" directive.

<nav ng-controller="LoginController as vm" ng-if="vm.isLoggedIn()" 
class="navbar navbar-inverse navbar-static-top" ng-init="vm.init()">

Within your login controller, make sure to return the authentication status of the user after successful validation.

function LoginController($http, $location, $window, AuthFactory, jwtHelper) {
    var vm = this;

    vm.isLoggedIn = function () {
        if (AuthFactory.isLoggedIn) {
            return true;
        }
        else {
            return false;
        }
    };
vm.login = function () {
        if (vm.username && vm.password) {
            var user = {
                username: vm.username,
                password: vm.password
            };

            $http.post('/api/users/login', user).then(function (response) {

                if (response.data.success) {
                    $window.sessionStorage.token = response.data.token;
                    AuthFactory.isLoggedIn = true;
                    var token =$window.sessionStorage.token;
                    var decodedToken = jwtHelper.decodeToken(token);
                    vm.loggedInUser = decodedToken.username;
                }
            }).catch(function (error) {
                console.log(error);   
            })
        }

    }

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

Implementing checkboxes for each API data in JavaScript

I am fairly new to this and I am currently working on a to-do list. I want to include a checkbox next to each item from the API to indicate whether it has been completed or not. <script type="text/javascript"> fetch('http://localhos ...

Working with node.js to set up an ordering function

I am working with node.js and express3. To use mongodb, I decided to install the mongo-lazy package. This is the simple GET router I have set up: var db = require('mongo-lazy').open({ db: 'somedb', host: '127.0.0.1' ...

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

What is the best way to handle an array (or manually loop through ng-repeat)?

AngularJS Version: 1.3.15 Confession: While I have limited knowledge of AngularJS, I am required to utilize it due to its integration in the framework I am working with. I aim to make changes to some HTML/AngularJS code that currently appears as follows: ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Tips for performing an integration test on a material UI <Slider /> component using either userEvent or fireEvent

I'm facing some challenges while trying to perform an integration test on a material UI component. I can locate the slider element, but have not been successful in moving the slider and retrieving the new value. Can you provide any guidance on how to ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

Is it advisable to employ jQuery(this) in this specific scenario?

My PHP script generates HTML a:link divs with different $linkname and $pageid values. It also creates corresponding jQuery scripts for each link: $output = '<a class="sig_lightbox_link" id="' . $pageid . '">' . ...

Retrieve information from a JSON key-value pair with the help of AngularJS

Is there a way in Angular's ngRepeat to extract a specific value from a JSON Array based on its key? I am working with the following JSON structure and would like to display the "Name 2" value for each object. { "Items": [ { ... "At ...

React Native: useEffect not triggering upon navigation to a screen that is already active

When I click on a notification in my React Native app, it navigates me to a chat screen. In that chat screen, there is a useEffect function that fetches the chat messages. The issue arises when the chat screen was the last screen opened before closing the ...

What is causing the issue with dynamic special characters not functioning properly in my React router?

I am working with 3 components named App.js, SearchCategoryPage.js, and Home.js. However, when I click on the search icon, it does not navigate me to the search page. What could be the reason for this issue? App.js const outlet_id = useSelector((state) =& ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

What is the importance of utilizing clearInterval to restart the timer in ReactJS?

Consider the code snippet provided below: useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); What is the purpose of returning ...

What are the best scenarios for utilizing ng-if over ng-show/ng-hide?

My comprehension is that ng-show and ng-hide act on the class assigned to an element, while ng-if determines if an element is displayed in the HTML document. Can you provide any instances where selecting ng-if over ng-show/ng-hide or vice versa would be m ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Retrieve the inner content of parentheses within a string, utilizing recursion for nested parentheses

I am currently working on a function that will extract words enclosed in parentheses and store them in their own array, accounting for nested parentheses recursively. For example, when given the string "((a b) ugh (one two)) pi", I would like it to be tra ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Having difficulties fetching data from Express server to React

My current project involves fetching data from an Express server to a React application using the Fetch API. The Express server interacts with a PostgreSQL database to retrieve relevant data that should be sent to the React frontend. The code snippets bel ...