attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected.

I have decided to implement this approach based on advice I received from others in a previous query where someone recommended using a resolve as the most logical solution.

This is the error message displayed in the console:

localhost:1337/lines/sports/undefined:1
GET http://localhost:1337/lines/sports/undefined 400 (Bad Request)

Please review my code below:

app.js

.state('app.sports', {
  url:'/sports',
  views:{
    menuContent:{
      templateUrl:'templates/sportsList.html',
      controller:'SportsController',
      resolve: {
        Sports: function(SportsFactory, AuthFactory, $q) {
          var defer = $q.defer();
          console.log(AuthFactory);
          AuthFactory.getCustomer().then(function() {
            SportsFactory.getSports().then(function(sports) {
              defer.resolve(sports);
            });
          });
          return defer.promise;
        }
      }

controller.js

.controller('SportsController', function($scope, $state,
             AuthFactory, SportsFactory, Sports) {
    $scope.query = '';
    $scope.sports = Sports;
    $scope.sports = [];
    $scope.customer = {};
   });

    AuthFactory.getCustomer().then(function(customer) {
      $scope.customer = customer;
      SportsFactory.getSportsWithLeagues(customer).then(function(sports) {           
        if (sports.length) {
          $scope.sports = sports;
        }else {
          AuthFactory.logout();
        }
      }, function(err) {
        console.log(err);
      });
    }, function(err) {
      console.log(err);
    });

service.js

.factory('SportsFactory', function($http, $q, AuthFactory,
          LocalForageFactory, LeaguesFactory, CONSTANT_VARS) {
    return {
      getSports: function(agent) {
        var defer = $q.defer();

        LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS)
          .then(function(sports) {
            if (!_.isNull(sports)) {
              defer.resolve(_.values(sports));
            }else {
              $http.get(CONSTANT_VARS.BACKEND_URL + '/lines/sports/' + agent)
                .success(function(sports) {
                  //forcing array instead of object
                  sports = _.values(sports);
                  sports = _.sortBy(sports, function(sport) {
                    return sport.priority;
                  });
                  LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS, sports);
                  defer.resolve(sports);
                })
                .error(function(err) {
                  defer.reject(err);
                });
            }
          });
        return defer.promise;
      },
      getSportsWithLeagues: function(customer) {
        var _this = this,
          defer = $q.defer(),
          rejection = function(err) {
            defer.reject(err);
          },
          sportsLength;

        LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES)
          .then(function(sportLeagues) {
            if (!_.isNull(sportLeagues)) {
              //forcing array instead of object

              sportLeagues = _.values(sportLeagues);
              defer.resolve(sportLeagues);
            }else {
              _this.getSports(customer.agent).then(function(sports) {
                sportsLength = sports.length;
                LeaguesFactory.getLeagues({
                  sportIds: _.pluck(sports, 'id'),
                  lineProfile: customer.lineProfile,
                  betLimit: customer.betLimit
                }).then(function(leagues) {
                  _.each(sports, function(sport) {
                    sport.leagues = _.filter(leagues, function(league) {
                      return sport.id === league.sport.id;
                    });
                  });
                  //forcing array instead of object
                  sports = _.values(sports);
                  LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES, sports);
                  defer.resolve(sports);
                }, rejection);
              }, rejection);
            }
          }, rejection);
        return defer.promise;
      }
    };
  });

and this is the authFactory:

.factory('AuthFactory', function($q, $http, $state,
          LocalForageFactory, CONSTANT_VARS) {
    return {
      /**
       * This function logs the customer, if the customer exists,
       * Customer data is saved in order to perform actions,
       * if not, an error message is returned.
       * @param credentials a json with this format {username: 'jhon', password:'D03'}
       * @returns {Animation.promise|promise}
       */
      login: function(credentials) {
        var defer = $q.defer(),
          _this = this;

        $http.post(CONSTANT_VARS.BACKEND_URL + '/auth/login',
          credentials
        ).success(function(data) {
            if (data.error) {
              defer.reject(data);
            }
            _this.setCustomer(data).then(function(customer) {
              defer.resolve(customer);
            }, function(err) {
              defer.reject(err);
            });
          }).error(function(data, status) {
            if (status === 0) {
              data = new Error('Backend is down');
              data.raw = {};
            }
            defer.reject(data);
          });
        return defer.promise;
      },
      setCustomer: function(customer) {
        var defer = $q.defer();
        LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
          /*Removing LocalForage Items*/
          LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
          LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
          LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
          defer.resolve(customer);
        }, function(err) {
          $state.go('app.login');
          defer.reject(err);
        });
        return defer.promise;
      },
      updateCustomer: function(customer) {
        var defer = $q.defer();
        LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
          defer.resolve(customer);
        }, function(err) {
          $state.go('app.login');
          defer.reject(err);
        });
        return defer.promise;
      },
      getCustomer: function() {
        var defer = $q.defer();
        LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_CUSTOMER).then(function(customer) {
          if (customer) {
            defer.resolve(customer);
          }else {
            defer.reject(new Error());
          }
          defer.reject(customer);
        }, function(err) {
          defer.reject(err);
        });
        return defer.promise;
      },
      logout: function() {
        var defer = $q.defer();

        this.getCustomer().then(function(credentials) {
          $http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout',
          credentials
        ).success(function(data) {
            if (data.error) {
              defer.reject(data);
            }
            /*Removing LocalForage Items*/
            LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
            LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
            LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
            LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER);
            defer.resolve(data);
          }).error(function(data) {
            defer.reject(data);
          });
        }, function(err) {
          $state.go('app.login');
          defer.reject(err);
        });
        return defer.promise;
      },
      updateToken: function(token) {
        var _this = this,
            defer = $q.defer();
        this.getCustomer().then(function(customer) {
          customer.token = token;
          _this.updateCustomer(customer).then(function(savedCustomer) {
            defer.resolve(savedCustomer);
          }, function(err) {
            defer.reject(err);
          });
        }, function(err) {
          defer.reject(err);
        });
        return defer.promise;
      },
      customerInfo: function() {
        var defer = $q.defer();
        this.getCustomer().then(function(customer) {
          $http.post(CONSTANT_VARS.BACKEND_URL + '/auth/info', customer)
            .success(function(data) {
              defer.resolve(data);
            })
            .error(function(err) {
              defer.reject(err);
            });
        }, function(err) {
          defer.reject(err);
        });
        return defer.promise;
      }
    };
  });

Answer №1

The app.js file is calling SportsFactory.getSports(), but it requires an 'agent' argument. Because you are not providing the 'agent', the URL being constructed is '/lines/sports/' + agent, which results in lines/sports/undefined. This causes a 400 (bad request) error. There could be other issues with the code, but this is the main reason for the error.

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

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...

`Error: Unresolved reference to Angular service`

I'm encountering an issue in my Ionic/Cordova application where I am trying to implement a loading message using $ionicLoading, but I keep getting the error: ReferenceError: $ionicLoading is not defined Does anyone know how I can successfully pass $ ...

Optimizing image centering in Next JS as screen size expands

I've been struggling to work with NextJS's Image component. My goal is to set up a banner image that only covers a specific amount of space on the screen, regardless of screen size. I have managed to achieve this by using max-height: 30vh and ov ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

What is the best way to customize the appearance of chosen selections in the MUI Autocomplete component?

I'm currently facing an issue with changing the style of selected options in MUI when the multi option is enabled. My goal is to alter the appearance of all highlighted options. Any assistance on this matter would be greatly appreciated, thank you! ...

Accessing new information seamlessly without the need for page refresh

For optimal mobile viewing of my website, I am considering implementing a select element. Here are the available options: HTML: <select name="select-choice-8" id="select-choice-nc"> <optgroup label="News"> & ...

Sort various divs using a list

I have multiple divs containing different content. On the left side, there is a list of various categories. When a category is clicked, I want to display the corresponding div for that category. Initially, I want the main category to be loaded, with no opt ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

simulate the act of clicking on a download link by utilizing a secondary click

adown is a link that allows users to download a file from my webpage. It functions properly on the page. However, btndown is a button designed to simulate clicking on the adown link, but unfortunately, it does not work as expected. When the btndown button ...

Can the selected week be highlighted along with the corresponding week number in a row?

Can we display the number of the week in a row along with the selected week, either in the toolbar or somewhere else? I attempted to utilize ToolbarComponent, but it overrides the entire header. However, I would like to keep it as is and just add informat ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

How can I execute a StoredProcedure using JavaScript?

I have a form with an email field and label <asp:TableRow runat="server"> <asp:TableCell runat="server"> <asp:TextBox runat="server" ID="txtUserEmail" onfocusout="emailVerification()" CssClass="forTe ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

The error "Cannot set headers after they are sent" is causing issues with the functionality of the Express session

Ensuring secure authentication for my Node.js application is a top priority. I have implemented the use of express-session npm to achieve this goal. The idea is that upon successful login on the /login page, a session should be initiated and the user shoul ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

Logging entire line syntax along with string output for debugging purposes

In my Vue.js application, there is a method that I have implemented. It goes like this: methods: { searchFunction(helper) { //helper.addFacetRefinement('deal', 'deal').search(); helper.addFacetRefinement('pri ...

When using SuperTest, the Authorization header value may unexpectedly return undefined

Currently, I am working on writing tests using Mocha, Supertest, and Chai. In order for my API's to function properly, they require an Authorization header which can be obtained from req.headers["authorization"]. Below you will find the current setup ...