【问题标题】:Can't resolve all parameters in AuthService无法解析 AuthService 中的所有参数
【发布时间】:2019-12-24 06:57:34
【问题描述】:

我在 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 的所有参数:(?, [object Object], [object Object], [object Object])。

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

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

【问题讨论】:

    标签: angular firebase firebase-authentication


    【解决方案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() {
      }
    
    }
    

    【讨论】:

    • 现在获取NullPointerException..core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[AuthService -&gt; AngularFirestore]: StaticInjectorError(Platform: core)[AuthService -&gt; AngularFirestore]: NullInjectorError: No provider for AngularFirestore!
    • 现在将AngularFirestore 放入提供者数组下的 login.module.ts 文件中。如果有帮助,请给予并投票并将其标记为答案。提前致谢
    • 是的,添加了它...但是得到相同的NullPointerException
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2017-09-26
    • 2018-03-24
    • 1970-01-01
    • 2016-11-27
    • 2018-05-16
    相关资源
    最近更新 更多