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

What is the method for linking images to URLs in my carousel?

I am in the process of revamping a confluence page that showcases a variety of visualizations. Here is the code snippet I am currently working with: <div class="carousel"> <img src="image1.jpg"> <img src="i ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1". ...

angular establish Header when an image is loaded

Every request to authenticate with the server requires a special value in the HTTP header. The code I am currently using is as follows: <img ng-if="content.image" src="{{img(content.image)}}"> and var app = angular.module('myApp', []); ...

Showing the URL beyond the search bar: A Guide using PHP, JavaScript, and HTML

How can I display the URL link outside the search box instead of opening a new page with the search result? I want to show the full URL (https://www.php.net.) below the search box, not within the search results. I only want to see the URL, not the contents ...

What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel: public class BusinessModel { public string BlobName { get; set; } public string NewName { get; set; } } In my MVC Ajax Controller, I have an action called DoBusiness: [HttpPost] public A ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Angular.js login redirection post authentication

I am finding it confusing on how to handle page redirection after successfully logging in using passport. Below is the node.js code snippet: app.post('/auth/login', passport.authenticate('local', { successRedirect: '/index.h ...

Interacting between Angular.js controllers and Polymer custom elements

Incorporating Angular.js and Polymer in my project has been a challenge, particularly when it comes to the communication between Angular.js controllers and Polymer custom elements. One specific issue I've encountered involves implementing an AuthServ ...

Using AngularJS to recycle computed variables

In my template, I am in need of utilizing a calculated value to hide certain elements and perform other actions. <button ng-hide="expensive()" ng-click="foo()">foo</button> <button ng-show="expensive() && otherFunction()" ng-click=" ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Div keydown event not being triggered in Vue

I've been struggling to get my event to fire despite following the instructions in the title. @keydown="keyPressed($event)" Although currently it looks like this, I have also attempted setting the tabIndex and adding it on mount as shown be ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...

Modify a unique element within an array stored in the state using Redux toolkit

I'm currently attempting to modify a property of an object within an array stored in my state. export const changeStatus = createAsyncThunk('changeStatus', async (arg) => { const todo = arg const response = await axios.put(`${URL} ...

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

What is the best way to extract a specific object from an array containing multiple objects?

Upon entry, there is an array with various objects. A function is needed to convert this incoming array of objects into a single object. The goal is to bring it to the desired form using the function provided. var array = [ { k1:v1 }, { k2:v2 }, ...

Having trouble displaying Ad-Gallery Loader.gif?

Having trouble with an image gallery I found at . The loader.gif image isn't showing up in IE9, just a red X. Being new to JavaScript, I'm struggling to fix this issue located at the top of the JavaScript file. (function($) { $.fn.adGallery = ...