Как исправить ошибку «Uncaught Error: невозможно разрешить все параметры для AuthService: (?).» - PullRequest
0 голосов
/ 09 апреля 2019

эта ошибка возникает при запуске приложения.Терминал не показывает какую-либо ошибку, но в консоли браузера.Последним действием было импортирование JwtHelperService из '@ auth0 / angular-jwt'

Проект в Nodejs, экспресс 4.16.4 и угловой 7.2.0 Я включил некоторый код, пожалуйста, помогите мне найти ошибку, спасибоВы заранее

auth.service.ts

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import "rxjs/Rx";
import { JwtHelperService } from "@auth0/angular-jwt";
import { map } from "rxjs/operators";
import "core-js/es7/reflect";

import { HttpClient } from "@angular/common/http";

const jwt = new JwtHelperService();
export class AuthService {
  @Injectable()
  private decodedToken;
  constructor(private http: HttpClient) {}
  public register(userData: any): Observable<any> {
    return this.http.post("/api/v1/users/register", userData);
  }
  public login(userData: any): Observable<any> {
    return this.http.post("/api/v1/users/auth", userData).map(token => {
      //debugger;
      return this.saveToken(token);
    });
  }

  private saveToken(token): string {
    //debugger;
    this.decodedToken = jwt.decodeToken(token);
    localStorage.setItem("bwm_auth", token.token);
    localStorage.setItem("bwm_meta", JSON.stringify(this.decodedToken));
    return token;
  }
} 

app.module.ts

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { Routes, RouterModule } from "@angular/router";

import { LoginComponent } from "./login/login.component";
import { RegisterComponent } from "./register/register.component";

import { AuthService } from "./shared/auth.service";

const routes: Routes = [
  { path: "login", component: LoginComponent },
  { path: "register", component: RegisterComponent }
];

@NgModule({
  declarations: [LoginComponent, RegisterComponent],
  imports: [
    RouterModule.forChild(routes),
    FormsModule,
    CommonModule,
    ReactiveFormsModule
  ],
  exports: [],
  providers: [AuthService]
})
export class AuthModule {}

ошибка в браузере

compiler.js:2430 Uncaught Error: Can't resolve all parameters for AuthService: (?).
    at syntaxError (compiler.js:2430)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:18984)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:18877)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getInjectableTypeMetadata (compiler.js:19099)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getProviderMetadata (compiler.js:19108)
    at compiler.js:19046
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (compiler.js:19006)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:18725)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (compiler.js:18555)

изображение ошибки в браузере

Ответы [ 2 ]

1 голос
/ 09 апреля 2019

@Injectable() следует поместить перед определением класса

 @Injectable()
 export class AuthService {

 }
0 голосов
/ 09 апреля 2019

Сначала вы должны добавить @ Injectable к вашему AuthService

Но эта ошибка указывает, что DI не может разрешить запрошенный параметр, запрашиваемый AuthService (HttpClient).

Чтобы решить эту проблему, вам нужно включить модуль HttpClient в ваш AppModule, как показано во фрагменте кода

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
     AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Вы можете увидеть их полную документацию здесь HttpModule

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...