Issue with AngularJS script halting when reaching factory function that returns a promise

I have been working on a beginner project that is essentially a simple task manager (similar to those todo list projects). I created a user login page for this project and here is how it functions.

There are two functions, siteLogin() for logging in, and inside it, I want to use the second function showTasks() after the user logs in. This function returns the user tasks obtained from an API using promises.

Initially, I encountered an issue when trying to return a value from an $http call within the showTasks() function. Instead of getting the desired value, it returned something like $$state. After researching solutions, I learned that $http doesn't return values but rather returns promises. Despite several attempts and failures, my code now runs up until the showTasks() function where it halts.

Here is a snippet of my current code:

Factory

app.factory('userTaskList', function ($http) {

    return {
        showTasks: function (userName) {
            var tasks = { K_ADI: userName }; //UserName of the per 
            var $promise = $http({
                method: 'POST',
                url: 'http://localhost:5169/api/Isler/' + userName + '/IstenilenKayitCek',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: tasks
            });
            $promise.then(function successCallback(response) {
                var data = response.data;
                console.log("Factory data:", response);
                return success(data);

            }, function errorCallback(response) {     
                error("Error");
            });
        }
    }
});

Controller:

 app.controller('myCtrl', ['$scope', '$http', function ($scope, $http,userTaskList ) {

 $scope.siteLogin = function () {
    var loginMember = {
        K_ADI: $scope.panel.loginUserName,  
        PAROLA: $scope.panel.loginPassword  // HTML input 
    };
    console.log(loginMember);
    $http({
        method: 'POST',
        url: 'http://localhost:5169/api/Kullanicilar/KullaniciDogrula',
        headers: {
            'Content-Type': 'application/json'
        },
        data: loginMember
    }).then(function successCallback(response) {
        console.log("Message sent", response);
        $scope.data = response.data.error.data;
        if ($scope.data === true) {

            console.log("User exists in database");

            //RUNS UNTIL HERE AND STOPS

            userTaskList.showTasks($scope.panel.loginUserName)
                .then(function (res) {
                    $scope.gorev = res;
                    console.log("Fonk ici : ", $scope.gorev);
                    console.log("222222", res);
                }, function (err) {
                    console.log(err);
                });
            console.log("outside func : ", $scope.gorev);     
        } 
    }, function errorCallback(response) {
        console.log("Error: ", response);
    });
}
}]);

Although this problem may seem repetitive as there are similar issues discussed on Stack Overflow, I have tried various solutions without resolving this particular problem and even encountered new ones along the way. I attempted using $q, nested .then, defining code in factories, and calling instances in modules, among other approaches, yet the issue persists.

NOTE: Apologies for any language errors in my explanation.

Answer №1

Identified multiple errors in the showTasks function:

app.factory('userTaskList', function ($http) {

    return {
        showTasks: function (userName) {
            var tasks = { K_ADI: userName }; //UserName of the per 
            var $promise = $http({
                method: 'POST',
                url: 'http://localhost:5169/api/Isler/' + userName + '/IstenilenKayitCek',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: tasks
            });
            var derivedPromise = $promise.then(function successCallback(response) {
                var data = response.data;
                console.log("Factory data:", response);
                ̶r̶e̶t̶u̶r̶n̶ ̶s̶u̶c̶c̶e̶s̶s̶(̶d̶a̶t̶a̶)̶;̶
                //IMPORTANT
                return data;

            }, function errorCallback(response) {     
                ̶e̶r̶r̶o̶r̶(̶"̶E̶r̶r̶o̶r̶"̶)̶;̶
                console.log(response.status);
                //IMPORTANT
                throw response;
            });
            //IMPORTANT
            return derivedPromise;
        }
    }
});

The required data should be returned to the .then method success handler.

Mistakes in the error handler must be re-thrown. Otherwise, the rejected promise will be converted to a success with a value of undefined.

Lastly, the derived promise needs to be sent back to the showTasks function.


Modification

Am I correctly invoking the function inside the $scope.siteLogin ?

The dependency injection is incorrect:

̶a̶p̶p̶.̶c̶o̶n̶t̶r̶o̶l̶l̶e̶r̶(̶'̶m̶y̶C̶t̶r̶l̶'̶,̶ ̶[̶'̶$̶s̶c̶o̶p̶e̶'̶,̶ ̶'̶$̶h̶t̶t̶p̶'̶,̶ ̶
    function ($scope, $http,userTaskList ) {

SHOULD BE

app.controller('myCtrl', ['$scope', '$http', 'userTaskList', 
    function ($scope, $http,userTaskList ) {

OR

app.controller('myCtrl', function ($scope, $http,userTaskList ) {

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

Showcase Pictures from a Document

Is there a way to upload an image via an input field and display it? I want to showcase a profile picture that can be saved in a database. The process should be simple for the user, with the ability to easily upload and view the image. function Save() { ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

What is the process for validating observations with an observer confirmation?

Can you explain what the of() function creates in this scenario and how it operates? public onRemoving(tag): Observable<any> { const confirm = window.confirm('Do you really want to remove this tag?'); return Observable.of(tag).fil ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

How can you change the text of a button in AngularJS until it finishes loading?

Is it possible to disable a button until it is fully loaded in AngularJS? I have created a directive to indicate the loading status of data and disable the button until the $http request is processed. However, I am facing an issue where the button automat ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

Tips for successfully passing a ViewBag in ng-click

<th><a href="javascript:;" ng-click="order(@ViewBag.desc)">Name</a></th> I am currently implementing this code and trying to fetch data from the view bag into my Angular Controller. However, I seem to be facing some challenges in a ...

Guide to programmatically configuring meta title, description, and image in a Vue.js project with the help of Vue Unhead and Vue Meta

I'm currently developing a Vue.js project where I need to dynamically set the meta title, description, and image based on data fetched from an API. To handle the meta tags, I am utilizing Vue Vue Unhead along with Vue Meta. Below is a snippet of the r ...

Semantic-release failing to generate a new version update for package

I'm in the process of setting up semantic release for my NPM package to automate deployment with version updates. However, after migrating from an old repo/npm package to a new one, I'm facing issues with semantic versioning not creating a new re ...

Any suggestions for a quicker method to manage state changes between OnMouseDown and OnMouseUp events in React?

I am attempting to create a window that can only be dragged from the top bar, similar to a GUI window. Currently, I have set up state updates based on OnMouseDown and OnMouseUp events on the top bar. However, I am experiencing slow updates as it seems to ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

How can I retrieve file input values in angularjs?

Currently, I am working on a simple application in AngularJS with the Slim framework. This application includes a form where users can input data such as their name, categories, currency, and an image file. While I am able to successfully retrieve data fro ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Expanding the size of a JavaScript array by adding fields

I have extended the JS array prototype by adding a "max" field. However, I am encountering difficulties in displaying this addition when stringifying the array. Despite attempting to modify the toJSON function, my efforts have been unsuccessful. Array.pro ...