首次使用Firebase,并尝试在Angular(v5)应用程序中设置电子邮件和Google身份验证。按照教程(https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/#Step-5-User-Profile)进行操作时,出现错误:
ERROR TypeError: Cannot read property 'user' of undefined
错误来自模板:
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) {
}
}
身份验证服务
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
this.user = this.afAuth.authState
.switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
} else {
return Observable.of(null)
}
})
}
googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
private oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> =
this.afs.doc(`users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL
};
return userRef.set(data)
}
signOut() {
this.afAuth.auth.signOut().then(() => {
this.router.navigate(['/']);
});
}
}
这个SO问题似乎相似,但是不确定答案如何应用于我的问题:firebase onAuth()抛出:TypeError无法读取未定义的属性“ auth”以及如何解决我的问题。
这是错误的屏幕截图:
Yurzui的上述解决方案解决了该问题。
我改变了constructor(public authService: AuthService)
对constructor(public auth: AuthService)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句