Angular: presenting items in navigation bar post logging in

I am relatively new to AngularJS and I am experiencing difficulties in displaying the userInfo in my navbar and showing the Logout button only when I am logged in.

1)

Currently, I am using ng-show to show the Logout button only when I am logged in, but the button appears in all scenarios.

2)

I am struggling to bind the userInfo received from the authentication service I created.

Navbar directive:

'use strict';

angular.module('clientApp')
  .directive('navbar', function() {
    return {
      restrict: 'E',
      templateUrl: 'views/shared/navbar.html',
      controller: 'NavigationCtrl'
    };
});

Navigation Controller:

'use strict';

angular.module('clientApp')
 .controller('NavigationCtrl', function ($scope, $location, authentication) {
   $scope.isActive = function(path) {
     return path === $location.path();
   };

   $scope.isLoggedIn = function() {
     return authentication.isLoggedIn;
   };

   $scope.userInfo = function() {
     return authentication.getUserInfo.firstname;
   };
});

Authentication Service:

'use strict';

angular.module('clientApp').factory('authentication', function($http, $q, 
$window, $location, ENV) {
var userInfo;

function init() {
  if ($window.sessionStorage.userInfo) {
    userInfo = JSON.parse($window.sessionStorage.userInfo);
  }
}
init();

function getUserInfo() {
  return userInfo;
}

function isLoggedIn() {
  return ($window.sessionStorage.userInfo) ? true : false;
}

isLoggedIn();

function login(user) {
  var deferred = $q.defer();

  $http.post(ENV.apiEndpoint + 'recruiters/auth', {
    email: user.email,
    password: user.password
  }).then(function(result) {
    userInfo = {
      appToken: result.data['app_token'],
      firstname: result.data['first_name']
    };
    $window.sessionStorage.userInfo = JSON.stringify(userInfo);
    deferred.resolve(userInfo);
    $location.path('/');
    $http.defaults.headers.common['Authorization'] = 'Oauth ' +
    userInfo.appToken;
  }, function(error) {
    deferred.reject(error);
  });

  return deferred.promise;
  }

  return {
    login: login,
    getUserInfo: getUserInfo
  };


});

Navabar.html:

<div class="header">
<div class="navbar navbar-default" role="navigation">
  <div class="container">
    <div class="navbar-header">

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#js-navbar-collapse">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>

    <a class="navbar-brand" href="#/">KDZ</a>
  </div>

  <div class="collapse navbar-collapse" id="js-navbar-collapse">

    <ul class="nav navbar-nav">
      <li ng-class="{active:isActive('/')}"><a href="#/">Home</a></li>
      <li ng-class="{active:isActive('/postings')}"><a ng-href="#/postings">Postings</a></li>
      <li ng-class="{active:isActive('/signup')}"><a ng-href="#/signup">Sign Up</a></li>
      <li ng-show="isLoggedIn">Logged as {{userInfo}}</a></li>
      <li ng-show="isLoggedIn"><a ng-href="#/logout"></a>Logout</li>
    </ul>
  </div>
</div>

I suspect that there may be an issue with the binding between the view, controller, or service, but I am having trouble identifying the exact problem. Does anyone have any suggestions or ideas on how to resolve this? Thanks!

Answer №1

1) The function isLoggedIn returns a truthy value, so the li element is displayed. Update it to use ng-show="isLoggedIn()". The same applies to the controller function where you return authentication.isLoggedIn;

2) Make sure to call the getUserInfo function correctly:

$scope.userInfo = function() {
    var userInfo = authentication.getUserInfo(); // Note the parentheses ()
    if (userInfo && userInfo.firstname)
        return userInfo.firstname;

    return 'unknown person';
};

Lastly, the 'authentication' service is missing an 'isLoggedIn' function. Modify the return value of the service to include it:

return {
    login: login,
    getUserInfo: getUserInfo,
    isLoggedIn: isLoggedIn
};

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

Ways to maintain group settings for a Telerik MVC Grid connected to Ajax

Currently, I am seeking guidance on how to persist grouping settings on an Ajax bound Telerik ASP .NET MVC grid. My goal is to have the grid display revert back to its previous settings when a user navigates away to a detail screen and then returns to the ...

Is it possible to utilize an Angular2 service with the DOM addEventListener?

Issue: I am encountering an problem where the service appears to be empty when trying to call it within an addEventListener. Html: <div id="_file0"> Service: @Injectable() export class FilesService { constructor(private http : Http) { } } Co ...

What could be causing my recursive function to skip over certain parts of my JSON data?

UPDATED TO BE MORE CONCISE Hello, I'm looking for assistance with a recursive function that's not returning the expected values from a JSON object. The goal is to retrieve all "Flow" object IDs where the "Type" is either "Standard" or "Block". T ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

What methods do developers employ to establish connections between pages in AngularJs?

As a new AngularJS developer, I have a good grasp on concepts like SPA and Components. However, one area that still confuses me is how to efficiently redirect users to different pages within an Angular app. I am seeking advice on the best approach for seam ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

Unable to show the response from an HTML servlet using Ajax and qTip2

I am having an issue where I am trying to display text (or html) received from a servlet response in a qTip2 tooltip within a jsp page. Despite verifying that the servlet is being invoked and returning text using Firebug, I encountered an error when attemp ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

The identical items combined into a single array

I have a specific data structure that I am struggling to manipulate in JavaScript. The goal is to merge objects with the same invoice_nr into one array, while keeping other objects in separate arrays. const result = [ { invoice_nr: 16, order_id: ...

Issues arising from TypeScript error regarding the absence of a property on an object

Having a STEPS_CONFIG object that contains various steps with different properties, including defaultValues, I encountered an issue while trying to access the defaultValues property from the currentStep object in TypeScript. The error message indicated tha ...

Make the checkbox font-weight bold when it is checked

Attempting to apply custom CSS to enhance the appearance of checkboxes using input and label elements. The goal is to make the font-weight bold when a user clicks on the checkbox, and then revert it back to regular if clicked again. Currently stuck on this ...

Exploring AngularJS: testing asynchronous $scope functions

I'm currently testing a controller method that interacts with the $scope object. This method initiates an asynchronous call and receives a promise in return. Once the promise is resolved, the resulting data is assigned to a variable within the $scope. ...

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

How to dynamically update form select options using Zend Framework 2 (2.3) and AJAX

I'm facing an issue with concatenating 3 dynamic selects - state, country, city - using an ajax request. It seems more complex without zf2! The function works fine when $idState is manually set within stateCountryCityAction (e.g. $idState = 1;), but d ...

Encountering a cannot POST / error while using Express

I am encountering an issue with my RESTful API while using Postman to call the route /websites. Despite my efforts, I keep receiving the error message "Cannot POST /websites". In addition, I am exploring the implementation of a job queue utilizing Express, ...

Triggering a function in response to a click

I'm encountering an issue with calling a callback inside a click event. Initially, I am attaching the click event to each table row. jQuery(tr).click(function (event) { var that = this; A(event, that, function () { var $gantt_containe ...

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

function called with an undefined response from ajax request in React

Hello, why am I getting the response "callback is not defined"? Component 1: console.log(getUserGps()); Component 2: import $ from 'jquery' export const getUserGps = () => { $.ajax({ url: "https://geolocation-db.com/jsonp", ...

HTML5's drag-and-drop feature, including nested targets, allows for intuitive and interactive user

I'm currently implementing HTML5 drag and drop functionality. I have a parent div that is droppable, and inside it, there is another child div that is also droppable. <div id="target-parent"> <div id="target-child"></div> </d ...

Choose the item to automatically reposition itself below once it has been opened

issue : The current behavior is that when the "other" option is selected, the input field appears. However, if I click on the select again, it covers up the input field. desired outcome : Ideally, I want the input field to show up when the "other" option ...