为什么我会出现静态喷油器错误?

时间:2019-01-22 23:32:46

标签: angular typescript

您好,我正在尝试为一个简单的角度应用程序创建登录名!但无论出于什么原因,我总是收到以下错误。

  

错误错误:“ 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 { }

我的login-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);
    }
}

2 个答案:

答案 0 :(得分:0)

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

providers: [
    AuthenticationService
  ],

答案 1 :(得分:0)

您使用的是哪个版本的angular?

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

如果您使用角度6或7,...,并且在服务元数据中使用{ providedIn: 'root' },则无需在app.module.ts的提供者部分中提供服务,只需您将需要在使用服务的组件中注入该服务。