Error handling in AngularJS and Firebase Promises

I am currently following a tutorial on thinkster.io and encountering some issues. The tutorial uses a deprecated SimpleLogin, so I have made the necessary code changes. However, I keep running into an error that says:

TypeError: Cannot read property 'finally' of undefined at Scope.$scope.register (http://localhost:9000/scripts/controllers/auth.js:9:31)

I suspect the problem lies within the promise in my controller logic. It seems to be returning undefined? Any assistance would be greatly appreciated. I can provide more details as needed. Thank you.

SERVICE LOGIC

'use strict';

app.factory('Auth', function ($firebaseAuth, $rootScope) {
  var ref = new Firebase('https://park-reservation.firebaseio.com/');
  //var auth = $firebaseSimpleLogin(ref);

  var Auth = {
    register: function (user) {
      return ref.createUser({
        email: user.email,
        password: user.password
      }, function(error, userData) {
        if (error) {
          switch (error.code) {
            case 'EMAIL_TAKEN':
              console.log('The new user account cannot be created because the email is already in use.');
              break;
            case 'INVALID_EMAIL':
              console.log('The specified email is not a valid email.');
              break;
            default:
              console.log('Error creating user:', error);
          }
        } else {
          console.log('Successfully created user account with uid:', userData.uid);
        }
      });
    },
    login: function (user) {
      return ref.authWithPassword({
        email: user.email,
        password: user.password
      }, function(error, authData) {
        if (error) {
          console.log('Login Failed!', error);
        } else {
          console.log('Authenticated successfully with payload:', authData);
        }
      });
    },
    logout: function () {
      ref.unauth();
    },
    resolveUser: function() {
      return ref.getAuth();
    },
    signedIn: function() {
      return !!Auth.user.provider;
    },
    user: {}
  };

  $rootScope.$on('login', function(e, user) {
    console.log('logged in');
    angular.copy(user, Auth.user);
  });
  $rootScope.$on('logout', function() {
    console.log('logged out');
    angular.copy({}, Auth.user);
  });

  return Auth;
});

CONTROLLER LOGIC

app.controller('AuthCtrl', function ($scope, $location, Auth, user) {
  if (user) {
  //  $location.path('/');
  }

  $scope.register = function () {
    Auth.register($scope.user).finally(function() {
      return Auth.login($scope.user).finally(function() {
        $location.path('/');
      });
    });
  };
});

Answer №1

The functions <code>createUser and authWithPassword in Firebase do not have return values, so attempting to call the finally method on an undefined value will result in an error.

It is important to include a new parameter (a callback function) in the register and login methods to handle responses from Firebase.

Update in the service:

  register: function (user, cb) {
      return ref.createUser({
        email: user.email,
        password: user.password
      }, function(error, userData) {
        if (error) {
          switch (error.code) {
            case 'EMAIL_TAKEN':
              cb('The email address is already in use.');
              break;
            case 'INVALID_EMAIL':
              cb('Invalid email provided.');
              break;
            default:
              cb('Error creating user:', error);
          }
        } else {
          // User account created successfully
          cb(null, userData.uid);
        }
      });
    },
    login: function (user, cb) {
      return ref.authWithPassword({
        email: user.email,
        password: user.password
      }, function(error, authData) {
        if (error) {
          //Login failed
          cb(error);
        } else {
          cb(null, authData);
        }
      });
    },

Update in the controller:

  $scope.register = function () {
    Auth.register($scope.user, function(err, userId) {
      if (err) {
        // Display error message 
        return;
      }
      // Include the userId returned by the register method in the user object
      $scope.user.Id = userId;
      Auth.login($scope.user, function(err, authData) {
        if (err) {
          // Display error message 
          return;
        }
        $location.path('/');
      });
    });
  };

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

Running "vue ui" with Node.js v17.2.0 - A step-by-step guide

After updating to Node.js v17.2.0, I am facing issues with running "vue ui" in my project. The error message I receive indicates a problem with node modules: at Object.readdirSync (node:fs:1390:3) at exports.readdir (/usr/local/lib/node_modules/@vu ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Retrieve a value using the jQuery each() method

Hello, I am a beginner in JavaScript and I need help with extracting values from JSON and adding them to an array. My goal is to be able to parse this array using another function later on. However, I'm struggling with returning the array after adding ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

How to Build a Custom Toolbar with Left and Right Aligned Elements using React.js and Material UI

Struggling with updating the toolbar on my website. Wanting the site name and logo on the left side, while login/sign-up buttons fixed to the right. Logo and title are in place, but can't get buttons to stay on right margin. Here's the code: func ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

Is utilizing unregistered HTML elements for semantic purposes considered poor practice?

When it comes to styling and semantic purposes, I am considering using unregistered web components. This means utilizing tags like <t-card></t-card> without registering them with customElements.define. Surprisingly, the browser and stylesheets ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

Placing JavaScript at the bottom of the page, sourced from a Partial Page

I'm trying to display JavaScript code from a Razor Partial Page at the bottom of a (layout) Page. In a similar discussion on Stack Overflow about Including JavaScript at bottom of page, from Partial Views, it was suggested by user Becuzz that using a ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Tips for creating a static background when displaying a modal popup in AngularJS

Incorporating a modal popup to modify a row within a grid view has been my recent task. Leveraging the row.getProperty() function, I successfully extracted the row values within the modal. However, an inconvenience emerged when attempting to edit a value ...

Display and conceal frequently asked questions using JQuery

I'm currently facing an issue with using JQuery to toggle between showing and hiding content when a user clicks on a specific class element. Here is my HTML code: <div class="faqSectionFirst"> Question? <p class="faqTextFirst" style=' ...

Modifying form data when submitting a form

Is there a common or widely-used method for modifying or adding form values before they are serialized and sent to the server upon form submission? I'm looking for a way to change or add these values without having to recreate them. I've come ac ...

Encountering an error message stating, "Unable to assign value to 'onclick' property"

Currently, I am at a beginner level in Javascript. While working on some exercises, I encountered an issue with the 'onclick' function as mentioned above. Despite going through other queries in this forum, I have not found a solution that works ...