首页 > 解决方案 > 无法解析 AuthService 中的所有参数

问题描述

AuthService在我的 Angular 代码中实现了。代码如下所示:

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>   

登录组件.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() {
  }

}  

身份验证服务.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 的所有参数:(?、[object Object]、[object Object]、[object Object])。

在 CompileMetadataResolver._getTypeMetadata ( compiler.js:20296) 在 CompileMetadataResolver._getInjectableTypeMetadata (compiler.js:20514)
在 CompileMetadataResolver.getProviderMetadata (compiler.js ) 的 syntaxError (compiler.js:2175) :20523) 在 compiler.js:20461 在 Array.forEach () 在 CompileMetadataResolver._getProvidersMetadata (compiler.js:20421) 在 CompileMetadataResolver.getNgModuleMetadata (compiler.js:20148) 在 JitCompiler._loadModules (compiler.js:25824)







这是循环依赖错误吗?使用forwardRef并不能解决它。

标签: angularfirebasefirebase-authentication

解决方案


试试这个 :

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() {
  }

}

推荐阅读