【问题标题】:why am i getting a static injector error?为什么我会收到静态注射器错误?
【发布时间】:2019-01-22 23:32:45
【问题描述】:

您好,我正在尝试为一个简单的 Angular 应用程序创建登录名!但无论出于何种原因,我不断收到以下错误。

错误错误:“StaticInjectorError[LoginModalComponent -> AuthenticationService]: StaticInjectorError(AppModule)[HttpClient]: StaticInjectorError(平台:核心)[HttpClient]: NullInjectorError: 没有 HttpClient 的提供者!”

过程是这样的,在主页上我有一个登录按钮,它是一个模态,我单击模态,然后弹出这个错误!我是初学者,不知道从哪里开始解决问题

这是我的 app.module.ts

   import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import { MatButtonModule, MatCheckboxModule } from '@angular/material';
   import { AngularFontAwesomeModule } from 'angular-font-awesome';
   import { NgbModule, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
   import { FormsModule, ReactiveFormsModule } from '@angular/forms';

   import { AppComponent } from './app.component';
   import { HomepageComponent } from './homepage/homepage.component';
   import { BrowserAnimationsModule } from '@angular/platform-browser  /animations';
   import { OpenStreetMapComponent } from './open-street-map/open-street-map.component';
   import { AppRoutingModule } from './/app-routing.module';
   import { LoginModalComponent } from './homepage/login-modal/login-modal.component';
   import { AddArtModalComponent } from './open-street-map/add-art/add-art-modal/add-art-modal.component';
   import { AddArtButtonComponent } from './open-street-map/add-art/add-art-button/add-art-button.component';
   import { RecommendButtonComponent } from './open-street-map/recommend-art/recommend-button/recommend-button.component';
   import { RecommendModalComponent } from './open-street-map/recommend-art/recommend-modal/recommend-modal.component';
   import { PopupsComponent } from './open-street-map/popups/popups.component';
   import { fakeBackendProvider } from './_helpers';

   @NgModule({
     declarations: [
       AppComponent,
       HomepageComponent,
       OpenStreetMapComponent,
       AddArtModalComponent,
       LoginModalComponent,
       AddArtButtonComponent,
       RecommendButtonComponent,
       RecommendModalComponent,
       PopupsComponent,
     ],
     imports: [
       BrowserModule,
       BrowserAnimationsModule,
       MatButtonModule,
       MatCheckboxModule,
       AngularFontAwesomeModule,
       AppRoutingModule,
       FormsModule,
       ReactiveFormsModule,
       NgbModule.forRoot()
      ],
      providers: [
        NgbActiveModal
      ],
      bootstrap: [AppComponent],
      entryComponents: [
        RecommendModalComponent,
        AddArtModalComponent,
        LoginModalComponent
    ]
    })
    export class AppModule { }

我的登录-modal.component.ts

import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { Router, ActivatedRoute } from '@angular/router';
import { FormsModule, FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { first } from 'rxjs/operators';

import { AuthenticationService } from '../../_services/authentication.service';


@Component({
  selector: 'app-login-modal',
  templateUrl: './login-modal.component.html',
  styleUrls: ['./login-modal.component.css']
})
export class LoginModalComponent implements OnInit {
  loginForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;
  error = '';


  constructor(
   public activeModal: NgbActiveModal,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService

  ) {
    //redirect to home if already logged in
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

    ngOnInit() {
      this.loginForm = this.formBuilder.group({
       username: ['', Validators.required],
       password: ['', Validators.required]
      });

      // get return url from route parameters or default to '/'
      this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    // convenience getter for easy access to form fields
    get f() { return this.loginForm.controls; }

    onSubmit() {
      this.submitted = true;

      // stop here if form is invalid
      if (this.loginForm.invalid) {
        return;
      }

      this.loading = true;
      this.authenticationService.login(this.f.username.value, this.f.password.value)
    .pipe(first())
    .subscribe(
      data => {
        this.router.navigate([this.returnUrl]);
      },
      error => {
        this.error = error;
        this.loading = false;
      });
}

}

还有我的 login.html

<div class="modal-content" tabindex="-1" role="dialog" aria-labelledby="Admin Login" aria-hidden="true">
  <div class="modal-header text-center">
    <h5 class="modal-title">Admin Login</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <div class="container">
      <form formGroup="loginForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="emailInput">Email:</label>
          <input type="email" formControlName="username" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email">
          <div *ngIf="submitted && f.username.errors" class="invalid-feedback">
            <div *ngIf="f.username.errors.required">Username is required</div>
          </div>
        </div>
        <div class="form-group">
          <label for="passwordInput">Password:</label>
          <input type="password" formControlName="password" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" class="form-control" id="inputPassword" placeholder="Password">
        </div>
        <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
          <div *ngIf="f.password.errors.required">Password is required</div>
        </div>
        <button routerLink="/map" type="submit" class="btn btn-primary signInButton modalButtons" (click)="activeModal.dismiss('Signed in')">Sign In</button>
      </form>
    </div>
  </div>
</div>

这里是 authentication.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { User } from '../_models';


@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    login(username: string, password: string) {
        return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }

                return user;
            }));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
    }
}

【问题讨论】:

  • 我在您的app.module.ts 中没有看到import { HttpClientModule} from "@angular/common/http";。也许尝试导入HttpClientModule
  • @Narm 不太确定!导入后,我得到一个完全不同的错误,一个语法错误,这不太有意义。 SyntaxError:“StaticInjectorError[LoginModalComponent -> AuthenticationService]:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”
  • 我也没有看到您在 app.module.ts 中导入您的 AuthenticationService。这需要导入并添加到您的 providers[] 数组中。
  • @Narm 仍然出现同样的错误

标签: angular typescript


【解决方案1】:

您错过了在 app.module.ts 中的 providers 数组中包含 AuthenticationService

providers: [
    AuthenticationService
  ],

【讨论】:

  • 我添加了它,但我仍然遇到同样的错误! SyntaxError:“StaticInjectorError[LoginModalComponent -> AuthenticationService]:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”
【解决方案2】:

你使用的是什么版本的角度?

对于低于 6 的版本,您需要在提供程序中的 app.module.ts 中导入并提供所需的服务,然后从服务中删除 { providedIn: 'root' }

如果您使用 Angular 6 或 7,...并且您在服务元数据中使用 { providedIn: 'root' },那么您不需要在 app.module.ts 的 provider 部分提供服务,只需注入您使用它的组件中的服务。

【讨论】:

  • 我使用的是 Angular 6!我完全按照你说的做,但错误仍然存​​在!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 2020-11-05
  • 2018-06-22
  • 2020-01-12
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多