我在Angular代码中实现了AuthService
。代码显示在这里:
login.component.html
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
<mat-card class="box">
<mat-card-header>
<mat-card-title>Log in to access FSRSolution</mat-card-title>
</mat-card-header>
<form class="example-form">
<mat-card-content>
<mat-form-field class="example-full-width">
<input matInput placeholder="emailid" #userEmail required>
</mat-form-field>
<mat-form-field class="example-full-width">
<input matInput placeholder="Password" #userPwd required>
</mat-form-field>
</mat-card-content>
<button mat-stroked-button class="btn-block login" (click) = 'authService.SignUp(userEmail.value, userPwd.value'>Log in</button>
<span class="orCenter">Or</span>
<button mat-stroked-button class="btn-block glogin" (click) = 'authService.GoogleAuth()'>Login with Google</button>
<button mat-stroked-button [routerLink]="[ '/register' ]" class="btn-block register">Register</button>
<a [routerLink]="[ '/forgot-password' ]" class="forgotpassord">Forgot Password?</a>
</form>
</mat-card>
</div>
login.component.ts
import { Component, OnInit, Inject, forwardRef } from '@angular/core';
import { AuthService } from '../../shared/services/auth.services';
@Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
constructor(@Inject(forwardRef(() => AuthService)) public authService: AuthService ) {
console.log(authService);
}
ngOnInit() {
}
}
auth.services.ts
import { Injectable, NgZone } from '@angular/core';
import { User } from './user';
import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
userData: any;
constructor( public afStore = AngularFirestore, public afAuth: AngularFireAuth, public router: Router, public ngZone: NgZone ) {
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
});
}
// Sign in with email/password
async SignIn(email: string, password: string) {
try {
const result = await this.afAuth.auth.signInWithEmailAndPassword(email, password);
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
});
this.setUserData(result.user);
} catch (error) {
window.alert(error.message);
}
}
async SignUp(email: string, password: string) {
try {
const result = await this.afAuth.auth.createUserWithEmailAndPassword(email, password);
this.sendVerificationMail();
this.setUserData(result.user);
} catch (error) {
window.alert(error.message);
}
}
async sendVerificationMail() {
await this.afAuth.auth.currentUser.sendEmailVerification();
this.router.navigate(['verify-email']);
}
setUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afStore.arguments(`users/${user.uid}`);
const userData: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoUrl,
emailVerified: user.emailVerified
}
return userRef.set(userData , {
merge: true
});
}
async forgotPassword(passwordResetEmail: string) {
try {
await this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail);
window.alert('Password reset email has been sent to registered email. Please check your email!');
} catch (error) {
window.alert(error.message);
}
}
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user != null && user.emailVerified !== false) ? true : false;
}
GoogleAuth() {
return this.AuthLogin(new auth.GoogleAuthProvider());
}
async AuthLogin(provider: auth.GoogleAuthProvider | auth.AuthProvider) {
try {
const result = await this.afAuth.auth.signInWithPopup(provider);
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
});
this.setUserData(result.user);
} catch (error) {
window.alert(error.message);
}
}
async signOut() {
await this.afAuth.auth.signOut();
localStorage.removeItem('user');
this.router.navigate(['register']);
}
}
在运行它时,它将引发以下错误:
未捕获的错误:无法解析AuthService的所有参数:(?,[对象对象],[对象对象],[对象对象])。
at语法错误(compiler.js:2175)
在CompileMetadataResolver._getDependenciesMetadata(compiler.js:20401)
在CompileMetadataResolver._getTypeMetadata(compiler.js:20296)
在CompileMetadataResolver._getInjectableTypeMetadata(compiler.js:20514)
在CompileMetadataResolver.getProviderMetadata(compiler.js:20523)
在compile.js:20461
在Array.forEach()
在CompileMetadataResolver._getProvidersMetadata(compiler.js:20421)
在CompileMetadataResolver.getNgModuleMetadata(compiler.js:20148)
在JitCompiler._loadModules(compiler.js:25824)
这是循环依赖性错误吗?使用forwardRef
不能解决问题。
答案 0 :(得分:1)
尝试一下:
import { Component, OnInit, Inject, forwardRef } from '@angular/core';
import { AuthService } from '../../shared/services/auth.services';
@Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
constructor(public authService: AuthService ) {
console.log(authService);
}
ngOnInit() {
}
}