One issue I've encountered is that Angularfire seems to have trouble reading the "facebook" property. So my question

I have been developing an android game using the ionic framework and firebase.

My goal is to implement a feature where users can log in using Facebook login with Firebase, and then save the game data to the user's database key.

The initial part of the process works smoothly. The script generates a database array based on the user's Facebook details. However, I encounter a challenge afterwards - Angular seems unable to modify any database data once this array is created. It appears that the authData gets stuck within the login function...

Is there a way to retain the authData for use in various controllers and functions?

app.factory("Auth", function($firebaseAuth) {
    var FIREB = new Firebase("https://name.firebaseio.com");
    return $firebaseAuth(FIREB);
});

app.controller('HomeScreen', function($scope, Auth, $firebaseArray) {
    Auth.$onAuth(function(authData){
        $scope.authData = authData;
    });
    var users = new Firebase("https://name.firebaseio.com/users/");
    // create a synchronized array
    $scope.users = $firebaseArray(users);
    $scope.facebooklogin = function() {

        Auth.$authWithOAuthPopup("facebook").then(function(authData){

            users.child(authData.facebook.cachedUserProfile.id).set({
                Username: authData.facebook.displayName,
                Id: authData.facebook.cachedUserProfile.id,
                Gender: authData.facebook.cachedUserProfile.gender,
                Email: authData.facebook.email,
                level: "1"
            });

        }).catch(function(error){

        });
    }
    $scope.facebooklogout = function() {
        Auth.$unauth();
    }
    $scope.changeLVL = function(authData) {
        users.child(authData.facebook.cachedUserProfile.id).set({
            level: "2"
        });
    }


});

This is the data structure it creates in firebase

 users
   998995300163718
     Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4608272b2306232b272f2a6825292b">[email protected]</a>"
     Gender: "male"
     Id:  "998995300163718"
     Username: "name lastname" 
     level: "1"

After attempting to edit, I receive this error message... (using the changelevel function)

TypeError: Cannot read property 'facebook' of undefined
    at Scope.$scope.changeLVL (http://localhost:8100/js/controllers.js:35:23)
    at fn (eval at <anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21977:15), <anonymous>:4:218)
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:57606:9
    at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24678:28)
    at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24777:23)
    at HTMLButtonElement.<anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:57605:13)
    at HTMLButtonElement.eventHandler (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12103:21)
    at triggerMouseEvent (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2870:7)
    at tapClick (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2859:3)
    at HTMLDocument.tapMouseUp (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2932:5)

Answer №1

It's important to note that relying solely on the cachedUserProfile.gender property may lead to errors as it may not be present for all users. It's advisable to have a fallback mechanism in place.

A simpler approach would be to pass the user using the resolve() method within the router. The code structure follows the guidelines outlined in the Angular Styleguide which I find effective for Angular applications.

angular.module("app", ["firebase"])
  .config(ApplicationConfig)
  .factory("Auth", Auth)
  .controller("HomeScreen", HomeController);

function Auth() {
  var FIREB = new Firebase("https://name.firebaseio.com");
  return $firebaseAuth(FIREB);
}

function ApplicationConfig($stateProvider) {
  $stateProvider
    .state("home", {
      controller: "HomeScreen",
      templateUrl: "views/home.html"
    })
    .state("profile", {
      controller: "ProfileScreen",
      templateUrl: "views/profile.html",
      resolve: {
        currentUser: function(Auth) {
          // Injecting authenticated user into the controller
          return Auth.$waitForAuth(); 
        }
      }
    });
}

function HomeController($scope, Auth, $state) {

  $scope.googlelogin = function() {

    Auth.$authWithOAuthPopup("google").then(function(authData) {

      users.child($scope.authData.google.cachedUserProfile.id).set({
        Username: $scope.authData.google.cachedUserProfile.id,
        Gender: $scope.authData.google.cachedUserProfile.gender || ""
      });

      $state.go("app.next");

    });
  }

}

function ProfileController(currentUser) {
  console.log(currentUser.facebook); // Injected from router
}

The advantage of this method is that you no longer need to verify the authentication status of users within the controller. By having the user injected, you can ensure an authenticated user is present.

For more details, refer to the AngularFire documentation.

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 is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

verified firebase/firestore requests

I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below: import { initializeApp } from "firebase/app"; import { getFirestore } from 'firebase ...

Switch the image source when hovering over a text menu

Currently, I have been using the following code to switch between images. However, what I actually want to do is change the image when hovering over the title link of the image. onmouseover="this.src='Images/img.png'" onmouseout="this.src=' ...

How can I retrieve and showcase the size of each file, including images, CSS, and JS, present on a website?

Currently, my goal is to create a dashboard capable of retrieving the file size for all resources (images, javascript, css, etc.) loaded on a webpage. I aim to then further filter these resources by file type and file size in order to identify which ones c ...

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

Checked boxes in the React dynamic checkbox list are not being marked

Can you please assist me with the following issue: I am in the process of creating a nested dynamic list of checkboxes for selecting companies and groups within those companies. Upon investigation, I have come up with the following code snippet const [ch ...

retrieve the status of a checkbox in a dynamically generated element

I'm currently working on integrating the YouTube API into my app in order to display a dynamic list of cards. The cards are stored in a variable and then added to a playlist container using an each function. Each card contains a toggle switch for use ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

What is the best way to obtain SAPUI5 Explored designs?

I am working on implementing a sap.ui.Table in my project, similar to the one showcased in the SAPUI5 Explored app. The table I am trying to create should allow for multi-selection of items using checkboxes on the left side. However, after downloading th ...

Attempting to confirm the accuracy of a data point within an extensive and interactive online table

I am facing a challenge in verifying a specific value from a large web table because none of the locators are unique and Selenium is unable to find all the elements. I am using Selenium and Cucumber JVM for automation. Below is a snippet of the HTML code ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Establishing the NumbroJS cultural settings

I have been attempting to modify numbro's culture. I initially tried the straightforward method, but encountered an error: Unknown culture : ' + code numbro.culture('fr-FR'); My attempt looked like this: const br = require('numb ...

Is it possible to deploy using Firebase and npm-installed binaries?

Looking to incorporate ffmpeg into my project, following the instructions provided here: https://github.com/firebase/functions-samples/blob/master/ffmpeg-convert-audio/functions/index.js With ffmpeg-static containing the necessary binaries, I am navigati ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

JavaScript frame malfunction causing page to continuously refresh

Once, I encountered a situation where my blog would display a frame or plugin when accessed from a particular website that I pinged. Wanting to remove this frame after 30 seconds, I managed to do so. However, the code I used resulted in my blog continuousl ...

Observing Node.js processes to track the peak memory usage of each process

Is there existing monitoring software that can track newly spawned node.js processes on my machine and display the maximum memory usage when the process ends? If not, how can this be achieved effectively? I have identified the specific Node.js processes I ...

Utilizing the Yelp API and/or the Google Places API for project development

Hey there! So I've been given a project for school that involves using either the Google Places API or Yelp API to allow users to search for local restaurants or bars near a specific location. I've spent the last couple of days researching how t ...

Unable to transfer the variable name between different node modules for the purpose of using it as a chat room identifier in a socket.io application

Users are able to provide a room name, however when using module.exports in a separate file to retrieve it, the value shows as undefined. This issue likely arises from the asynchronous nature of the process. //roomcheck.js var nsp = io.of("/gameroom"); n ...

Ensuring that jQuery(document).ready(function() contains the appropriate content

Recently, I've been attempting to integrate a javascript gallery into my WordPress site. However, I'm encountering some confusion regarding what needs to be included in the .ready(function) to successfully run the gallery. The original jQuery fun ...