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

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

Utilize an AngularJS controller to verify the presence of a cookie and display a modal pop-up

In the process of developing a Single Page Application (SPA), I have encountered an issue with an HTML element calling an AngularJS controller. Here is what I need: I want the controller to check for a specific cookie: - If the cookie exists, call a ...

AngularJS is not displaying the full value of the model in the user interface

I have a technique for saving an object into an array after modifying some of its properties. However, I am facing an issue where not all the modified properties reflect in the user interface. Code : HomeController.js $scope.MainArray=[]; $scope.newIt ...

JavaScript utilizes regex patterns to modify the value located between the characters within an input's name attribute

Can anyone assist me in creating a unique regex pattern to extract specific characters from the attribute values of HTML inputs? I'm dynamically cloning select elements and input text with button clicks, so I need to maintain the attribute name synta ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

Mixing up jQuery's Deferred, jsDeferred, and the concept of deferring in coding can be a common source of confusion

I recently downloaded a library called jsdeferred in hopes of resolving some code-flow issues I've been facing. However, I'm finding the examples and documentation to be a bit unclear. In my quest for clarity, I also discovered that jQuery offers ...

Is there a way to extract the values from a range slider individually and then display them as the minimum and maximum values on the screen?

Currently, I am facing an issue with a range slider where the value I am retrieving is concatenated. For example, when printed, it appears as 2080, with 20 and 80 being separate values visually combined on screen. My goal is to extract the minimum and maxi ...

Is it possible to duplicate this jQuery/Javascript feature using PHP?

I have the code to fetch tweets in JavaScript, but I need it converted to PHP. Can anyone provide any guidance on how to achieve this? $(document).ready( function() { var url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1 ...

Vue.js Ajax call is throwing a bizarre error: TypeError - str.replace function not recognized

Recently, I encountered a puzzling error message: vue-resource.common.js Uncaught TypeError: str.replace is not a function while working on an ajax call to retrieve some data: export default { data: () => ({ recipes: [] }), ready() { ...

"Troubleshooting issue: Vue deep watch failing to detect changes in object properties

My initial data consists of a `customer` object. As I input text into various fields, different keys are added to the object. The watcher function triggers properly when a new key is added, but if an existing key is edited with a new value, the watcher doe ...

What is the best way to utilize hosting rewrites for seamless integration between Firebase hosting and cloud functions?

Unique content for a more specific description I am experimenting with using Express and Firebase functions for advanced routing purposes. However, I encountered an error when attempting to access my Firebase cloud function. TypeError: Cannot read prop ...

Vue Router consistently triggers browser reloads, causing the loss of Vuex state

I encountered an issue that initially appeared simple, but has turned out to be more complex for me: After setting up a Vue project using vue-cli with Router, VueX, and PWA functionalities, I defined some routes following the documentation recommendations ...

Executing pure JavaScript code in Grails using Groovy

this is a duplicate of Executing groovy statements in JavaScript sources in Grails with a slight variation, my intention is to only render the js-code without enclosing it in script tags picture someone loading a script from my server within their html l ...

How to access dropdown menu within modal using Angular version 1.29 and the most recent update of Chrome (

We are encountering an issue with a standard <select> dropdown that is positioned within a modal used by an Angular component. This functionality was functioning properly prior to the update to Chrome 47, but now it no longer works -- there are no vi ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...