Is my application of using promise accurate?

Recently, I started learning angularJs and I am currently working on implementing login/logout functionality in my application.

In order to achieve this, I have created an AuthService that facilitates user login and a SessionService that stores the authentication token in local storage (I am using jwt).

This is how the AuthService looks like:

'use strict';

angular.module('App')
.factory('AuthService', ['ApiService', 'SessionService', '$q', '$timeout', 'jwtHelper', function (ApiService, SessionService, $q, $timeout, jwtHelper) {

    // inherit
    var service = Object.create(ApiService);

    service.login = login;
    service.logout = logout;
    service.check = check;
    service.user = user;

    return service;

    function login(credentials) {
        return service.form('user.login', credentials)
            .then(function success(response) {
                SessionService.setToken(response.token);
                return response;
            });
    }

    function logout() {

        // Implementing a promise for easier handling 
        // of logout in the controller

        var d = $q.defer();

        $timeout(function () {
            SessionService.setToken();
            d.resolve();
        }, 0);

        return d.promise;
    }

    function check() {
        var token = SessionService.getToken();
        return !!token && !jwtHelper.isTokenExpired(token);
    }

    function user() {
        return service.call('user', {cache: true});
    }

}]);

I'm experiencing an issue with the logout method. Since there is no server call involved, all I need to do is clear the local storage to log the user out. However, I prefer to handle this using a promise so that in the controller I can use the following approach:

       function logout() {
        AuthService.logout().then(function success() {
            $state.go('login');
        });
    }

Do you think this is a good way to achieve the logout functionality?

Answer №1

Why bother with making a promise in your case? Here's an alternative approach:

Instead of using a promise, store an "authenticatedUser" object in the $rootScope with any relevant parameters (such as user culture, roles, or just a boolean).

In an "applicationController", implement a $watch function to monitor changes to the authenticatedUser value:

$rootScope.$watch('authenticatedUser', function(newVal, oldVal){
    if (newVal == oldVal)
        return;

    if (newVal == null){ // User has logged out
        // Clear the screen
        // Show the login form
    }
});

Then in your controller, simply use:

function logout() {
    AuthService.logout();
}

This way, if you ever need to log out from another controller in the future, you can simply call your service without duplicating code.

There's something puzzling in your code:

// inherit
var service = Object.create(ApiService);

Keep in mind that in Angular, every service is a singleton created during application startup. Are you intentionally deviating from this default behavior?

  • : Be cautious with $watches, as they can consume a lot of processing time during Angular digest cycles.

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

Retrieving information from subscription

I am currently diving into Angular 2 and have successfully fetched data from my service. However, before displaying it on the view, I need to iterate over it using a for() loop. To achieve this, I have stored the fetched JSON data into an array. But I&apos ...

Manipulating SVG image color using JavaScript

Is there a way to change the colors of an svg image using Javascript? Perhaps by loading it as an object and accessing the color/image data? I would greatly appreciate any responses or tips on this matter! ...

Storing data on the server for your Cocos2d JavaScript game

I've been struggling with implementing a savegame option for my cocos2d JavaScript game. After following a tutorial from Ray Wenderlich (thanks, Ray!), I gave up on trying to do it client-side and am now looking into saving XML files to a web server w ...

The Bootstrap switch feature may encounter issues when trying to operate on dynamically generated checkbox inputs

My website is equipped with a mix of essential scripts: jQuery, Bootstrap, Modernizer, and JSON2HTML. I am trying to implement the following code snippet: <script> $('#my01Switch').bootstrapSwitch({ onText: 'ON', ...

How is it possible for me to access any route beyond localhost and still reach my homepage?

Currently, I am working on a ReactJs project that utilizes a REST API to fetch information about Pokemon including stats, names, and images. Despite setting up my Routes using React Router, I am encountering an issue where all routes redirect me to the sam ...

Determine the frequency of a specific key in an array of objects

original array: ................ [ { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7e19e6b26621247a35cd"} } ] A new array is created to count the instances of each ...

Navigating to the present child state with modified parameters can be achieved using the following steps

Check out this demo: https://jsfiddle.net/explorer/622qzqsc/ In the platform I'm working on, we have an advanced concept of state management, specifically for building timelines. In the template of this system, there's a code snippet (which is c ...

Switch the measurement unit in the .dotdotdot script from pixels to percentages for the height value

I'm looking to convert the height value from 100 pixels to a percentage, specifically 50%. I have limited experience with javascript... <script language="javascript" type="text/javascript"> $(document).ready(function(){ $(".item-info-overla ...

Issue with Ajax: parameters failing to pass without using jQuery

It appears that I am only receiving jQuery results, but I am in search of the correct method to pass parameters via AJAX without using libraries or old browser fallbacks. If there is another thread discussing this topic that I have overlooked, please provi ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

Can you confirm if this email address is legitimate?

"Sophie Dupont"@sample.com While diving into RFC 5321 in an attempt to fully grasp the concept of a valid email address, I find myself overcomplicating things unnecessarily. This topic has been on my mind lately. i.e., within a quoted str ...

Angular is patiently waiting for the initial function to activate

I have a situation where I need to wait for the results of my first function before executing the second one. code First function getUser() { this.authService.user().subscribe( user => { this.user = user; console.log('c ...

Getting a portion of a div ID through jQuery or JavaScript

In the contents of my webpage, there is a specific division element that appears as follows: <div id="entry-7265">...</div> Is there a way to extract only the numerical part of this div's ID using either jQuery or JavaScript? I am not int ...

How to Retrieve Element's Boundaries in Angular 2 Component

I am working on a component that functions as a popover. Here is the structure of the component: import {Component, Input, ViewChild} from 'angular2/core' declare var $: any; @Component({ selector: 'popover', template: ` <di ...

Strategies for Managing Output Event Prioritization in Angular Using RxJs Based on Trigger Sequence

Within my Angular Application, there is a widget with two event outputs originating from a third-party library. Unfortunately, I am unable to modify its behavior. <myWidget (onAlwaysEvent)="onAlwaysEvent($event)" (onSometimesEvent)="onSometimesEven ...

Tips for getting information from a GET/POST response message with superagent

I'm currently utilizing Node.js and Superagent for testing my server implementation. I have successfully sent a Superagent GET request and received a positive response with the code provided below. My goal is to extract and log only the "id" value fro ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

After incorporating some movement effects into my menu, suddenly none of the buttons were responding

While working on my website and trying to add a close menu button, I encountered an issue where all the menu buttons stopped functioning. Here is the HTML code snippet: <div id="openMenuButton"> <span style= "font-size:30px;cu ...

The unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere. I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue ...