Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts.

In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (.success), I create a cookie with myCookieSrv.createCookie.

Once the cookie is created successfully, my goal is to invoke another service - myAuthSrv.validateUser

Controller:

app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {

    myAuthSrv.authUser($scope.data)
        .success(function (data, status, headers, config) {
                var cookieName = 'myCookieName';
                myCookieSrv.createCookie(cookieName, Id, 1);
                    //////////////////////////////////////////////
                    //.then(console.log("call promise here!!!"))
                    //.catch(error)
                    //////////////////////////////////////////////
            }
        })
        .error(function (data, status, headers, config) {
            $scope.err = "Something has gone wrong";
        })
});

myCookieSrv:

app.service('myCookieSrv', function() {
    return {
        createCookie : function(cookieName, Id, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else var expires = "";
            document.cookie = cookieName+"="+Id+expires+"; path=/";

        },
        readCookie : function(cookieName) {
            var nameEQ = cookieName + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        }
    }
});

Upon successful execution of myCookieSrv.createCookie, the plan is to call validateUser from myAuthSrv:

app.service('myAuthSrv', function($http) {
    this.authUser = function() {
        return $http({
            method: 'POST',
            url: 'some url',
            data: {},
            headers: {'Content-Type': 'application/json'}
        });
    }

    this.validateUser = function() {
        return $http({
            method: 'POST',
            url: 'some url',
            data: {},
            headers: {'Content-Type': 'application/json'}
        });
    }  
}

Answer №1

To avoid any issues, make sure not to create a promise immediately after creating a cookie. Instead, modify the controller code as shown below:

app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {

    myAuthSrv.authUser($scope.data)
        .then(function () {
            var cookieName = 'myCookieName';
            myCookieSrv.createCookie(cookieName, userId, 1);
        })
        .then(function () {
           return myAuthSrv.validateUser();
        })
        .then(function () {
           // handling success case
         }, function () {
            $scope.err = "An error occurred";
        })
});

Answer №2

Try a similar approach

let loggedInUser = userService
                                .loginUser($scope.userInfo);

                        loggedInUser
                                .then(
                                        function(response) {
                                            //add your logic here (response contains the returned data)
});

Answer №3

Here is a solution that may be beneficial.

app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {
myAuthSrv.authUser($scope.data)
    .success(function (data, status, headers, config) {
            var cookieName = 'myCookieName';
            myCookieSrv.createCookie(cookieName, Id, 1);
                myAuthSrv.validateUser()
                .success(function(){
                    //Authentication Successful
                })
                .error(function(){
                    //There was an error in authentication
                });
        }
    })
    .error(function (data, status, headers, config) {
        $scope.err = "Oops! Something went wrong";
    })
});

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

When scrolling down, the popup window shifts its position

I have implemented a popup window which displays a list on hover. It works perfectly on the default page, but when I scroll down, the popup also moves with the scrollbar. Below is the HTML code that creates the hidden popup list initially and shows it on ...

Is there a way to automatically update the URL to include $_GET['data'] (media.php?data=123) when a selection is made from a dropdown list?

I'm currently working on a project that involves a website in PHP and a MySQL database. I have successfully linked the two together, and now I have a combobox filled with data from the database. Below is my script for handling the selection: <scr ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...

Is there a way for me to record the input field's value to the console every time it is altered?

Currently, I am diving into the angularjs phonecat tutorial (specifically step 5) in an effort to grasp a deeper understanding of how angular operates. However, I have been struggling to successfully log the input field value to the console. Despite trying ...

Managing errors in React Router on the server-side

I am currently working on an isomorphic application using react-router and express. My goal is to implement custom error pages that will be displayed in case of server-side errors, rendering errors, or when a page is not found. However, I am facing difficu ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Limit the execution speed of a JavaScript function

My JavaScript code is set up to trigger a click event when the user scrolls past a specific element with the class .closemenu. This is meant to open and close a header menu automatically as the user scrolls through the page. The problem I'm facing is ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Struggling with running my React App as I'm encountering some errors

Check out the code on Github: https://github.com/bhatvikrant/IndecisionApp I have already run npm i and then executed yarn run dev-server, utilizing webpack. My operating system is MacOs. I have also created the .babelrc file. The issue I encountered aft ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

What is the best way to conceal a ModalPopupExtender that is integrated into an ASCX user control without triggering a postback, utilizing JavaScript?

I am currently working on an Asp.net application and have encountered an issue with the ModalPopupExtender embedded within an ASCX user control. I am trying to set up a cancel button that will hide the popup without triggering a post back when clicked. He ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Node.js and the concept of handling null values

console.log("variable = " + JSON.stringify(result.something)); After running the code, I see that variable = null However, when I add this condition: if (result.something != null || result.something != '') { console.log('entered' ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

Triggering the AJAX function in the main window

My HTML webpage has a hyperlink that, when clicked, opens the same page in another window with a hash value appended to the URL using window.open. For example, the URL could look like this: http://mywebsite.com#hash=value The webpage contains a JavaScript ...