繁体   English   中英

无法解析 Angular 上 AuthService 的所有参数

[英]Can't resolve all parameters for AuthService on Angular

我正在尝试启动我的 Angular 应用程序,但由于某种原因,我在下面收到此错误。 我尝试从我的组件中删除身份验证服务提供程序,并从我的组件内的构造器中删除身份验证服务,但没有任何改变......我无法弄清楚我做错了什么,我是角度的初学者。

错误:

Can't resolve all parameters for AuthService: (?, ?, [object Object]).

我的组件:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../Services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthService]
})

export class LoginComponent {

  isUserLoggedIn: boolean;
  emailAddress: string;
  password: string;
  invalidLogin: boolean;
  invalidText: string;

  constructor(private authService: AuthService, private router: Router) {

    if (authService.getCurrentUser() != null) {
      router.navigate(['/home']);
    }
  
  }

  login() {
    
    if (!this.authService.login(this.emailAddress.toString(), this.password.toString())) {
      this.invalidLogin = true;
      this.invalidText = "Wrong Email Address or password";
    }
    
  }

}

我的服务:

import { Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { UserModel } from "../Models/UserModel";

export class AuthService {

    constructor(private router: Router, private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {}

    login(email: string, password: string) {

        const headers = {'Content-Type': 'application/json', };
        const body = { emailAddress: email, password: password };
        let userLoggedIn: Boolean = false;

        this.http.post<any>(this.baseUrl + "Api/Login", body, { headers }).subscribe(response => {
            
            if (response.username != null) {
                let user: UserModel
                user = response;
                this.router.navigate(['/home']);
                this.saveUserToLocalStorage(user);
                userLoggedIn = true
            }

        }, error => console.error(error)); 
        return userLoggedIn;
    }

    saveUserToLocalStorage(loggedInUser: UserModel) {
        sessionStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
    }

    getCurrentUser() {
        return sessionStorage.getItem("loggedInUser")
    }

    logout() {
        sessionStorage.removeItem("loggedInUser")
        this.router.navigate([''])
    }

    createUser(userData: UserModel) {}

    sendResetPasswordEmail() {}

}

我认为这是因为您在构造函数中使用了Router ,请尝试这样做

constructor(private readonly injector: Injector,
           ...) {}

public get router(): Router {
   return this.injector.get(Router);
}

我发现了问题所在。 我必须将我的服务类标记为@Injectable()

像这样:

@Injectable()
export class SchoolService {
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM