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: