Troubleshooting issues with logging out in AngularJS

After attempting to logout of my current session, I realized that the logout feature is not working. Below is the code I have used:

view

<a ui-sref="logout">
   <i class="fa fa-sign-out"></i> Log out
</a>

config.js

$stateProvider
            .state('logout', {
                url: "/logout",
                templateUrl: '',
                controller: "LogoutController"
            });

controllers.js

function LogoutController($location, $http) {
    alert("hi");
    //Session.clear();
    var request = $http({
        method: "post",
        url: "users/ajaxLogout",
        dataType: 'json',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
    request.success(function(data) {

    });
    $location.path('/login');
}

angular
   .module('inspinia')
   .controller('MainCtrl', MainCtrl)
   .controller('LogoutController', LogoutController);

Although I have placed an alert in the LogoutController, it seems that the function is not being triggered when I click the Log out link.

I referred to this Angular - Logout redirect route for guidance. Kindly review my code and let me know where the error may be occurring.

Answer №1

To implement the logout functionality, it is advisable to encapsulate the code inside a function in your controller:

function LogoutController($location, $http, $scope) {

    this.logout = function() {
        alert("hi");
        //Session.clear();
        var request = $http({
            method: "post",
            url: "users/ajaxLogout",
            dataType: 'json',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        });
        request.success(function(data) {
            $location.path('/login');
        });

    }
}

Next, you can trigger the logout function by using ng-click when the logout link is clicked:

<div ng-controller="LogoutController as ctrl">
<a ui-sref="logout">
   <i class="fa fa-sign-out" ng-click="ctrl.logout()"></i> Log out
</a>
</div>

Answer №2

Ensure to check the console to see if there are any errors being generated and attempt the following:

  angular .controller('LogoutController', function($scope,$state,$location,$ionicHistory, $http) {
    console.log("hello");
     $state.go('app.login');
     $ionicHistory.clearCache();
    };

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

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Dealing with null route parameters for Express applications

I am facing a challenge in handling an empty route parameter when a path is not specified. My intention is to return a new date if the route parameter is empty. However, the server's response so far is: Cannot GET /api/timestamp/ app.get("/api/timest ...

Apply a unique design to a class by clicking on a button

There are 3 identical boxes with the same classes and a button: function changeColorAndAddPadding() { /* ??? */ } .box { border: 1px solid; display: inline; } <button onclick="changeColorAndAddPadding();">Click Here</button> <d ...

Tips on maintaining the content of an element within a directive template

I'm currently facing an issue with adding the ng-click directive to a button. Here's my HTML: <button class="btn">clicky</button> This is the directive I am using: angular.module('app').directive('btn', function ...

``Promise rejection triggered when a boolean value is passed to $q.when`

In the code snippet below, $q.when is used to resolve a promise with either true or false. It is known that $q.when will always resolve and never be rejected. When passing a boolean value to this segment, it is observed that the error callback function is ...

Implement a JavaScript confirm dialog for a mailto hyperlink

Is there a way in javascript to automatically detect mailto links on the page and prompt a confirmation dialog when clicked by a user? I came across a method on this website for displaying an alert message. My knowledge of javascript is very basic. It&ap ...

How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility ...

The spawn function in the child_process module throws an error with the code -2, specifically the

Hey there, I'm working on creating an npx command that allows me to run child commands within my package.json bin: "bin": { "malzahar": "./src/bin/malzahar.js" }, Below is the code from my malzahar.js: #! /usr/bin/en ...

Adjust the border color of Material UI's DatePicker

https://i.sstatic.net/ZvNOA.png Hello everyone, I am currently working with a DatePicker component from Material UI. My main goal is to change the border color of this component. I have attempted various methods such as modifying classes, adjusting the th ...

Is there a way to randomly rearrange an array of objects when the page loads, then iterate over the rearranged array without triggering a console warning about "two children with the same key"?

When shuffling the array and mapping over it in my application, I am able to correctly display the shuffled data using translate3d for a slider effect. However, I keep receiving a growing list of console warnings: "Encountered two children with the s ...

Navigating Angular: A Beginner's Guide to Routing

As I delve into the world of Angular and embark on creating my very first app, I find myself in need of assistance with setting up routing. Directory Layout spa/ index.html controllers/ controllers.js images/ javascript/ app.js resource ...

Retrieve four distinct values using only a single text box input and display them individually on separate lines

Is there a way to receive four input values from the user using just one textbox and display them on separate lines? function collectData() { var userInput, i; var textOutput = " "; for (i = 0; i <= 3; i++) { userInput = document.g ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Is it possible to return true to asp.net OnClientClick following an Ajax request? Alternatively, is there another method that can be used?

I am currently implementing an Ajax call to verify if a user is logged in. If the user is not logged in, I want to display a login dialog; otherwise, I need OnClientClick to return true so that the form can be submitted. I am considering using a global var ...

Tips for creating a consistent header and footer across an HTML CSS web application

My previous projects involved using ASP.NET MVC and utilizing @Html.Partial("_header") to incorporate common static HTML across different pages. However, my current project is a pure HTML CSS and JS web app with no server-side technology. The la ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

Is it possible for a Javascript code to execute multiple tasks upon being inserted into the browser's URL bar?

Is it feasible for JavaScript to simulate a user clicking on a link, triggering a pop-up, automatically clicking a button within the pop-up, and then redirecting the user to a final page once a specific code is copied and pasted into the browser's add ...

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...

Mongoose Alert: Unable to Create Schema Instance

Below is the Schema file that I'm using: const mongoose = require("mongoose"); const ProblemSchema = new mongoose.Schema( { slug: { type: String, required: true, unique: true, }, title: { type: String, ...