无法解析 AuthService 的所有参数:([object Object], ?) Angular 5.x

Posted

技术标签:

【中文标题】无法解析 AuthService 的所有参数:([object Object], ?) Angular 5.x【英文标题】:Can't resolve all parameters for AuthService: ([object Object], ?) Angular 5.x 【发布时间】:2018-06-22 08:42:26 【问题描述】:

我对 Angular 2-5 非常陌生,这是我第一次尝试在教程之外的任何内容中设置服务。我收到“无法解析所有参数”错误消息,我不知道需要解析哪些参数以及为什么不需要解析。谁能帮帮我?我会尽可能多地包含代码。

auth.service.ts

import  Injectable  from '@angular/core';
import  HttpClient, HttpHeaders  from '@angular/common/http';
import  Observable  from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import  ClientJs  from 'clientjs';
import  AnyoneGuard  from '../components/guards/anyone.guard';
import  Constants  from '../app.config';


@Injectable()
export class AuthService 
  constructor(private http: HttpClient, private clientJs: ClientJs)  

  ipAddress: any;
  user: any;

  public isLoggedIn() 
    return this.user.isAuthenticated;
  

  getIp(login) 
    const client = new this.clientJs;
    const fingerprint = client.getFingerprint();
    console.log('FINGERPRINT: ' + fingerprint);
    this.ipAddress = fingerprint;
    if (login)  return fingerprint; 
    return '&IpAddress=' + fingerprint;
  

  clearUser() 
    this.user = 
      username: null,
      authtoken: '',
      isAuthenticated: false,
      roles: null,
      ip: null,
      opName: null,
      opId: null,
      opMode: null,
      opPartition: null
    ;
  

  public login(username: string, password: string): Observable<boolean> 
    return this.http.post<any>(Constants.API_URL + 'authservice/login',
       username: username, password: password, IpAddress: this.getIp(true) )
      .map(results => 
        let loggedIn = false;

        if (results) 
          const authToken = results.data.authToken + this.getIp(false);
          if (authToken) 
            loggedIn = true;
          

          this.user = 
            username: results.data.username,
            authtoken: authToken,
            isAuthenticated: loggedIn,
            roles: results.data.roles,
            ip: results.data.ip,
            opName: results.data.opName,
            opId: results.data.opId,
            opMode: results.data.opMode,
            opPartition: results.data.opPartition
          ;

          console.log('authService:Login: ' + JSON.stringify(this.user));

          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(this.user));
        

        return loggedIn;

      );
  

  public logout(): Observable<boolean> 

    return this.http.post<any>('http://localhost:58510//api/authservice/logout',  username: this.user.username )
      .map(results => 
        console.log('authService:Logout: ' + JSON.stringify(this.user));

        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');

        this.clearUser();

        return false;
      );

  

login.component.ts

import  Component, OnInit  from '@angular/core';
import  ActivatedRoute, Router  from '@angular/router';
import  FormGroup, FormControl, Validators, FormBuilder  from '@angular/forms';
import  Constants  from '../../../app.config';
import  AuthService  from '../../../services/auth.service';
import  NGXLogger  from 'ngx-logger';

@Component(
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less'],
    providers: [NGXLogger]
)

export class LoginComponent implements OnInit 

    copyright: string;
    version: string;

    form: FormGroup;

    username = new FormControl('', Validators.required);
    password = new FormControl('', Validators.required);

    constructor(fb: FormBuilder, private route: ActivatedRoute, private router: Router, private authenticationService: AuthService, private logger: NGXLogger) 
        this.form = fb.group(
            'username': this.username,
            'password': this.password // ['', Validators.required]
        );

        this.copyright = Constants.COPYRIGHT;
        this.version = Constants.VERSION;
    

    onSubmit() 
        const isLoggedIn = this.authenticationService.login(this.form.value.username, this.form.value.password);

        if (isLoggedIn) 
            this.logger.info('logged in as : ' + this.form.value.username);
            // console.log('logged in as : ' + this.form.value.username);
         else 
            this.logger.warn('logged failed');
            // console.log('login failed');
        

        this.router.navigate(['/dashboard', this.form.value.username],  relativeTo: this.route );
    

    ngOnInit() 
    


app.module.ts

// Angular Imports
import  BrowserModule  from '@angular/platform-browser';
import  NgModule  from '@angular/core';
import  CanActivate, CanActivateChild, CanDeactivate, Routes, RouterModule  from '@angular/router';
import  ReactiveFormsModule, FormControl, FormsModule  from '@angular/forms';
import  HttpClientModule, HttpClient  from '@angular/common/http';

// Components
import  AppComponent  from './app.component';
import  LoginComponent  from './views/noauth/login/login.component';
import  DashboardComponent  from './views/dashboard/dashboard.component';
import  FooterComponent  from './components/common/footer/footer.component';
import  CardholderComponent  from './views/cardholder/cardholder.component';
import  AccesslevelComponent  from './views/accesslevel/accesslevel.component';
import  SearchComponent  from './views/search/search.component';
import  ControlComponent  from './views/control/control.component';
import  ReportComponent  from './views/report/report.component';
import  BadgeComponent  from './views/badge/badge.component';
import  EditCardholderComponent  from './views/cardholder/edit-cardholder/edit-cardholder.component';
import  EditBadgeComponent  from './views/badge/edit-badge/edit-badge.component';
import  EditAccessLevelComponent  from './views/accesslevel/edit-access-level/edit-access-level.component';
import  EditControlComponent  from './views/control/edit-control/edit-control.component';

// Services
import  AuthService  from './services/auth.service';

// Guards
import  AnyoneGuard  from './components/guards/anyone.guard';
import  LoggedInGuard  from './components/guards/logged-in.guard';
import  AdminGuard  from './components/guards/admin.guard';

// Libs
import  NgbModule  from '@ng-bootstrap/ng-bootstrap';
import  TranslateModule, TranslateLoader  from '@ngx-translate/core';
import  TranslateHttpLoader  from '@ngx-translate/http-loader';
import  LoggerModule, NgxLoggerLevel  from 'ngx-logger';
import  ClientJs from 'clientjs';

// Pipes
import  KeepHtmlPipe  from './components/pipes/keep-html.pipe';

// Routes
import  ROUTES  from './app.routes';

// Layouts
import  BasicLayoutComponent  from './components/common/layouts/basic-layout/basic-layout.component';
import  BlankLayoutComponent  from './components/common/layouts/blank-layout/blank-layout.component';
import  TopNavigationLayoutComponent  from './components/common/layouts/top-navigation-layout/top-navigation-layout.component';
import  NavigationComponent  from './components/common/navigation/navigation.component';
import  TopNavbarComponent  from './components/common/top-navbar/top-navbar.component';
import  TopNavigationNavbarComponent  from './components/common/top-navigation-navbar/top-navigation-navbar.component';

@NgModule(
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    FooterComponent,
    CardholderComponent,
    AccesslevelComponent,
    SearchComponent,
    ControlComponent,
    ReportComponent,
    BadgeComponent,
    EditCardholderComponent,
    EditBadgeComponent,
    EditAccessLevelComponent,
    EditControlComponent,
    KeepHtmlPipe,
    BasicLayoutComponent,
    BlankLayoutComponent,
    TopNavigationLayoutComponent,
    NavigationComponent,
    TopNavbarComponent,
    TopNavigationNavbarComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule.forRoot(ROUTES),
    NgbModule.forRoot(),
    LoggerModule.forRoot(serverLoggingUrl: '/api/logs', level: NgxLoggerLevel.DEBUG, serverLogLevel: NgxLoggerLevel.ERROR),
    TranslateModule.forRoot(
      loader: 
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      
    )
  ],
  providers: [
    AuthService,
    AdminGuard,
    AnyoneGuard,
    LoggedInGuard
  ],
  bootstrap: [AppComponent]
)
export class AppModule  

export function HttpLoaderFactory(http: HttpClient) 
  return new TranslateHttpLoader(http);

【问题讨论】:

【参考方案1】:

Angular 无法注入 ClientJs,因为它不知道如何注入。

为了注入一些东西,它必须在某个providers数组中,并且可能是@Injectable()

如果你想注入它,你可以写一个封装它的类,或者直接实例化它而不注入它

【讨论】:

以上是关于无法解析 AuthService 的所有参数:([object Object], ?) Angular 5.x的主要内容,如果未能解决你的问题,请参考以下文章

Nest 无法解析 AuthService 的依赖项(AuthRepository,?)

NestJS 无法解析 AuthServices 的依赖关系

Istio authservice oidc 无法交换访问令牌的授权码

用于tomcat的OpenAm代理无法读取authservice url?

NGXS 错误:无法解析 TranslationEditorState 的所有参数:(?)

错误:无法解析ContactService的所有参数:(?)