Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL

This is being done using Angular functions.

Here is the code snippet:

HTML:

<img ng-src="{{getImg(user.uid)}}" alt="">

Javascript:

$scope.getImg = function(uid) {
  // return uid;
    promise = firebase.database().ref("/users/" + uid + "/info/").once("value");
    promise.then(function(snapshot) {
      return snapshot.val().photoURL;
    }, function() {
      return "Error :(";
    });
};

Encountering:

TypeError: snapshot.val(...) is null

Alternate approach attempted:

firebase.database().ref("/users/" + uid + "/info/").once("value").then(function(snapshot) {
     return snapshot.val().photoURL;
 });

No data returned with this method either.

Edit:

Structure of the data trying to load:

  "[user uid]" : {
    "info" : {
      "name" : "Jett Jackson",
      "photoURL" : "[URL to photo]"
    }
  }

Edit: Used in ng-repeat and for a single user.

Edit: Surrounding code snippet provided:

route.controller("dashController", ["$scope", "$http", "$routeParams", "$firebaseArray", "$firebaseObject", "$sce", function($scope, $http, $routeParams, $firebaseArray, $firebaseObject, $sce) {
    var postsRef = firebase.database().ref().child("posts"),
    query = ($firebaseArray(postsRef), postsRef.orderByChild("timestamp").limitToLast(5));
    $scope.posts = $firebaseArray(query);

    firebase.auth().onAuthStateChanged(function(user) {
        user ? $scope.user = user : $scope.user.displayName = "Signed Out";
    });
    $scope.getImg = function(uid) {
  // return uid;
    promise = firebase.database().ref("/users/" + uid + "/info/").once("value");
      promise.then(function(snapshot) {
        return snapshot.val().photoURL;
      }, function() {
        return "Error :(";
      });
   };

}]);

HTML:

In the posts section:

  <div ng-repeat="post in posts | reverse" class="item">
    <a href="/#/post/{{post.$id}}"><div class="img">
      <img src="{{post.thumbnail}}" alt="">
    </div></a>
      <div class="column center-vert">
        <h1>{{post.title}}</h1>
        <p>{{post.preview}}</p>
      <div class="icons row">
        <i class="icon-heart"></i>{{post.starCount}}<div class="pad"></div><i class="icon-user"></i>
        <div class="timestamp">12 hours ago</div>
      </div>
    </div>
      <div class="author">
      <img src="{{getImg(post.uid)}}" alt="">
      <p>{{post.author}}</p>
    </div>
  </div>

In the user view:

<div class="userImageContainer">
  <img ng-src="{{getImg(user.uid)}}" alt="">
</div>

Answer №1

Begin by examining the facebase API to determine if it contains a val() function or not. In the callback function, note that the return value (snapshot) may be undefined.

// Check if snapshot has a val()
snapshot.val()

Answer №2

This script assumes that when post.uid is equal to user.uid

In relation to the issue with the user, it becomes available only after the onAuthStateChanged event is triggered. Therefore, until that point, $scope.user remains empty or unknown.

One solution is to trigger an event using $broadcast once the user information is retrieved within the onAuthStateChanged function and then utilize $on as shown below:

$scope.UserProfilePhoto = ""; // initialize profile photo URL

firebase.auth().onAuthStateChanged(function (user) {
    user ? $scope.user = user : $scope.user.displayName = "Signed Out";
    $scope.$broadcast('user-logged-in'); // broadcast that the user is now logged in
});

// listen for user log in event
$scope.$on('user-logged-in', function (event, args) {
    // at this point, the user id should be available. Call your getImg function
    $scope.UserProfilePhoto = $scope.getImg($scope.user.uid);
});

$scope.getImg = function (uid) {
    // return uid;
    promise = firebase.database().ref("/users/" + uid + "/info/").once("value");
    promise.then(function (snapshot) {
        return snapshot.val().photoURL;
    }, function () {
        return "Error :(";
    });
};

html

<img ng-src="{{UserProfilePhoto}}" alt="">

We would appreciate if you share how it worked out. Additional reading material can be found at

Answer №3

After running into issues with using angular functions in a ng-repeat loop, I found a solution by updating my code to the following:

My Posts:

var postsRef = firebase.database().ref().child("posts");
    query = ($firebaseArray(postsRef), postsRef.orderByChild("timestamp").limitToLast(5));
    $scope.posts = $firebaseArray(query);
    $scope.posts.$loaded(function() {
      var length = $scope.posts.length;
      for (var i = 0; i < length; i++) {
          var uid = $scope.posts[i].uid;
          if ($scope.postUser[uid]!==undefined){
          } else {
            ref[uid] = firebase.database().ref().child("/users/" + uid + "/info/");
            $scope.postUser[uid] = $firebaseObject(ref[uid]);
          }
      }

User Information:

$scope.$on('user-logged-in', function (event, args) {
        var ref = firebase.database().ref().child("/users/" + $scope.uid + "/info/");
        $scope.user = $firebaseObject(ref);
    });

This adjustment should have been made earlier, according to some arguments.

Special thanks to @Searching for the valuable assistance! <3

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

Replace existing styled-component CSS properties with custom ones

One of my components includes a CheckBox and Label element. I want to adjust the spacing around the label when it's used inside the CheckBox. Can this be achieved with styled()? Debugging Info The issue seems to be that the className prop is not b ...

pass boolean value from middleware to express route handler

In a middleware I have defined, my aim is to fetch and return a boolean value like this: module.exports = { authenticatepracticename: function(pname) { ecollection.find({ $and: [{'name':pname},{'status' : 'active&apos ...

"Troubleshooting a blank page issue in Angular UI Router caused by query string

I've been struggling with an issue related to query string parameters for quite some time. When I navigate to /, everything works perfectly fine. However, if I try something like /?anything, it simply doesn't work. These are the configurations in ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

Having trouble toggling webcam video in React/NextJS using useRef?

I have created a Webcam component to be used in multiple areas of my codebase, but it only displays on load. I am trying to implement a toggle feature to turn it on and off, however, I am facing difficulties making it work. Below is the TypeScript impleme ...

Is it possible to change the background color using jQuery?

Can you assist me with this: I have a website and I am looking to modify the bg-coler when hovering over the menu (similar to how it works on the rhcp-website). I attempted using jquery for this, but unfortunately, it did not yield the desired result.. ( ...

"Is there a way to ensure that jPlayer plays the same song even after a page refresh

I have been working on integrating jPlayer with Ajax to ensure that when the page of my website is refreshed, jPlayer will continue playing its current song seamlessly. I have successfully stored track information and the current track during refresh, ho ...

Notify when a certain element's ID is visible on the screen using the jQuery appear method

Having trouble getting this plugin to cooperate: https://github.com/morr/jquery.appear I attempted to reference the plugin from a CDN using Ajax: http://cdnjs.cloudflare.com/ajax/libs/jquery.appear/0.3.3/jquery.appear.js Why isn't it working as expe ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

Discovering the specific DOM element that has been clicked using only JavaScript

Looking to enhance my HTML document with interactivity, I wanted to achieve a feature where clicking on a div element would display its respective id. I attempted the following approach: window.onload = function() { associateIds(); clicked(); } fu ...

Adjust top position dynamically during resizing

When resizing the window, I am facing an issue with the image going outside of the box. I believe adjusting the position top of the image based on the box height might help in fitting the image properly within the box. $(window).resize(function() { va ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

Utilizing the output from a console.log in a webpage

Although the function I created is functioning properly and successfully outputs the value to my terminal onSubmit, I am facing difficulty in understanding why this code isn't updating my html. router.post('/index', function(req, res, next) ...

Finding a specific section on a webpage using AngularJS

Is it possible to create in-page navigation to a specific section within an Angular application without triggering the routing service? For example: The section we want to jump to: <a name="tips"> <div>Tips and tricks...</div> < ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

Is utilizing AngularJs for a Single Page Application (SPA) in a DDD project a wise decision?

Embarking on a new journey to implement an enterprise app following DDD principles. As my team and I delve into this world, we have much to learn and understand (please forgive any novice questions). The focus will be on creating a highly customized CMS. ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...