Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error:

ERROR TypeError: Cannot read property 'user' of undefined

The error originates from the template:

login.component.html

<div *ngIf="auth.user | async; then authenticated else guest">
  <!-- template will replace this div -->
</div>
<!-- User NOT logged in -->
<ng-template #guest>
  <h3>Howdy, GUEST</h3>
  <p>Login to get started...</p>

  <button (click)="auth.googleLogin()">
    <i class="fa fa-google"></i> Connect Google
  </button>
</ng-template>
<!-- User logged in -->
<ng-template #authenticated>
  <div *ngIf="auth.user | async as user">
    <h3>Howdy, {{ user.displayName }}</h3>
    <img  [src]="user.photoURL">
    <p>UID: {{ user.uid }}</p>
    <p>Favorite Color: {{ user?.favoriteColor }} </p>
    <button (click)="auth.signOut()">Logout</button>
  </div>
</ng-template>

login.component.ts

import {Component} from '@angular/core';
import {AuthService} from '../auth/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

  constructor(public authService: AuthService) {
  }
}

auth.service.ts

import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import * as firebase from 'firebase/app';
import {AngularFireAuth} from 'angularfire2/auth';
import {AngularFirestore, AngularFirestoreDocument} from 
'angularfire2/firestore';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap'

interface User {
  uid: string;
  email: string;
  photoURL?: string;
  displayName?: string;
  favoriteColor?: string;
}

@Injectable()
export class AuthService {

  user: Observable<User>;

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore,
              private router: Router) {
    //// Get auth data, then get firestore user document || null
    // code block here
  }

  googleLogin() {
    const provider = new firebase.auth.GoogleAuthProvider()
    return this.oAuthLogin(provider);
  }

  private oAuthLogin(provider) {
    // code block here
  }

  private updateUserData(user) {
    // code block here
  }

  signOut() {
    this.afAuth.auth.signOut().then(() => {
      this.router.navigate(['/']);
    });
  }
}

This Stack Overflow question appears relevant, but it's unclear how the solution applies to my issue: firebase onAuth() throwing: TypeError cannot read property 'auth' of undefined. How can I address the problem effectively?

Provided below is a screenshot of the encountered error:

https://i.sstatic.net/JyTog.png

Answer №1

By implementing Yurzui's solution, I successfully resolved the problem at hand.

The modification made was switching from

constructor(public authService: AuthService)
to
constructor(public auth: AuthService)
.

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 causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Steps to troubleshoot and resolve the @ionic/angular member Event error in Ionic 5

Recently I made the switch from Ionic 4 to Ionic 5, and now I am encountering this error: ERROR in src/app/app.component.ts(4,10): error TS2305: Module '"/node_modules/@ionic/angular/ionic-angular"' has no exported member 'Events'. ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

The Aurelia application encounters a "Maximum call stack size exceeded" error while trying to bind FullCalendar

I am currently working on setting up a JQuery plugin (FullCalendar) within my Aurelia application, which is built using TypeScript. I am relatively new to web development and just trying to get a basic example up and running. To start off, I utilized this ...

Set up a Pinia store with a specific data type

Note: I am a beginner in JavaScript I am currently working on synchronizing an object with a Pinia store and a Python REST API. My goal is to define a type just once without having to duplicate it in the store. export const useTicketStore = defineStore(&a ...

Local variables are now being refreshed with every modification in the data stored in Cloud Firestore

Having trouble maintaining the accuracy of my local variables in sync with changes to the data in cloud firestore. Specifically, in my local variable called count_vehicle, the value represents a count based on specific conditions from the data in cloud fir ...

Angular 10 is not displaying images despite receiving the image path from an API

Despite my API returning the image path for the product, my Angular application is not displaying the image. HTML Code <ng-container *ngFor="let prod of productData"> <div class="row p-2 bg-white border rounded" styl ...

Tips for inserting a pin into a designated location on an image map

Within my angular application, I have implemented an image map using the HTML usemap feature. Here is the code snippet: <img src="../../assets/floor2.jpg" usemap="#floor2Map"> <map name="floor2Map"> <area shape="pol ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Encountering an issue while attempting to retrieve a key from an Object within an Observable using async functionality

I have a seemingly basic and simple Object that I retrieve using Rx and would like to display a portion of it on screen. I removed all HTML and simply added {{ structure$ | async | json }}, with structure$ being the name of the Observable in my component, ...

Guide on implementing ng-if in an Ionic 2 HTML template

To display records if found and show "no records found" otherwise, I have implemented the code below: <div ng-if="program.videourl"> <video width="100%" controls="controls" preload="metadata" webkit-playsinline="webkit-playsinline" class="vide ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Issue when generating Angular production build due to module not being found

I've encountered a problem while building an Angular module with angular cli and calling it in another project. Everything works fine when I run ng serve, but I am facing an error when running ng build --prod: ERROR in ./node_modules/my-module/dis ...

Typescript: Enhance your coding experience with intelligent parameter suggestions for functions

Within a nest.js service, there is a service method that takes an error code and generates a corresponding message to display to the user. The example below shows a simplified version of this method: getGenericErrorMessage(input: string): string { co ...

When attempting to build a production version of an Angular Ionic Capacitor project, a TypeError occurred stating that it cannot read the property 'updateClassDeclaration'

A short while back, I didn't encounter this error, but after executing npx audit fix --force, I started getting this error when running npm run build in my Ionic capacitor project: Module build failed (from ./node_modules/@angular-devkit/build-angular ...

Can a personalized component be displayed as a tooltip?

I find the existing tooltip design too complicated to work with. Are there any alternatives such as creating a new component to use instead? ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

The app.module.js is in need of the most up-to-date version of Angular

I have just started learning Angular. I recently installed angular cli and angular material ui, but when I opened my project and checked the folder, I noticed that the app.module.js file was missing. I don't understand why this happened. Instead, I fo ...