Despite being logged, the current value of firebase.auth().currentUser in Firebase is null

I have coded a query in my service.TS file that displays the "state" of items based on the UID of the logged-in user:

getLists(): FirebaseListObservable<any> {

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {console.log("blah", firebase.auth().currentUser.uid)
    // User is signed in.
  }
});
  return this.db.list('/foods', {
    query: {
      orderByChild: 'state/'+firebase.auth().currentUser.uid+'/state',
      equalTo: 'listed'
    }
  });
}

However, I encountered an error message that says:

Uncaught (in promise): TypeError: null is not an object (evaluating 'WEBPACK_IMPORTED_MODULE_2_firebase_app"auth".curren‌​tUser.uid').

Despite the fact that

{console.log("blah", firebase.auth().currentUser.uid)
successfully displays the UID in the log when the user is signed in.

Just to clarify, this query is being invoked by the main TS file of the page with:

    ngOnInit() {

    this.moviesSvc.getLists()
                  .subscribe(lists => {console.log(lists); console.log("UID", firebase.auth().currentUser.uid); this.lists = lists})
  }

Any suggestions on how to properly pass the UID to the query?

Answer №1

Utilizing the onAuthStateChanged() method is essential because it operates asynchronously. This means that it is crucial to ensure that the user's unique identifier (uid) is present within its callback before proceeding with any operations. The following example demonstrates how this can be achieved:

fetchItems(): FirebaseListObservable<any> {

    var self = this;

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is authenticated.
            var userID = user.uid;

            return self.db.list('/products', {
                query: {
                    orderByChild: 'owner/' + userID + '/id',
                    equalTo: '12345'
                }
            });
        }
    });

}

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

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...

Height and placeholder issue with ion-searchbar

Hey there, I hope everything is going well for you. I've encountered a problem with the Ionic 5 - Angular Searchbar feature. This is how I added the searchbar: <ion-searchbar [(ngModel)]="text" (ionChange)="sear ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

What is the best way to import a geojson file into Express.js?

I'm currently trying to read a geojson file in Node.js/express.js. The file I am working with is named "output.geojson". I want to avoid using JSON.parse and instead load it using express.js (or at least render it as JSON within this function). var o ...

How do I reduce the size of a WinJS image file

Can anyone help me figure out how to retrieve the size (in pixels, bytes) of a picture in a Windows 8 app? I'm using openPicker to select the file but can't seem to find the size attributes. I want to display an error message if the file is too ...

What is the method for verifying the types of parameters in a function?

I possess two distinct interfaces interface Vehicle { // data about vehicle } interface Package { // data about package } A component within its props can receive either of them (and potentially more in the future), thus, I formulated a props interface l ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator: ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'" To access these elements, we can compile all the ones with fa-minus and store them in a lis ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

There are a few steps to take in order to sort an array of objects by a

I want to organize and display data in a sortable table format javascript let dataList = [ { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number, index: number }, { idx: number, name: string, btn: number ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

What is the method to adjust the color of <pagination-controls>?

Seeking assistance with customizing the color of angular pagination from blue to a different hue. Any suggestions? https://i.stack.imgur.com/JjcWk.png I've experimented with various code snippets, but unfortunately, none have yielded the desired res ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

What sets React.HTMLProps<HTMLDivElement> apart from React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>?

Exploring the differences between interfaces and types in React: interface Properties1 extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {} interface Properties2 extends React.HTMLProps<HTMLDivElement> ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

Performing a sequence of actions using Jquery Queue() function and iterating through each

I am facing an interesting challenge with an array called result[i]. My goal is to iterate through each field in the array and add it to a specific element on my webpage. $("tr:first").after(result[i]); However, I would like this process to happen with a ...

Searching for a JavaScript tool that offers syntax highlighting capabilities

I have come across some excellent RTE HTML text editors such as jsredaktor, TinyMCE, and FCK Editor, but I am in search of an HTML/JavaScript component that functions similarly to a TEXTAREA with built-in code syntax highlighting. ...

Why is the 3rd argument necessary when using useReducer?

According to the information provided in the documentation: [init, the 3d argument] allows you to separate the logic for determining the initial state outside of the reducer. This is particularly useful for resetting the state later in response to an ac ...