Angular4注入Http未定义

时间:2017-05-09 08:03:26

标签: angular dependency-injection angular2-services

我正在构建这个自定义服务,用于调用Mock后端来验证用户身份。

身份验证服务:

import 'rxjs/add/operator/map';
import { Headers, Http, Response } from '@angular/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthenticationService {

  constructor(private http: Http) {}

  login(username: string, password: string) {
        return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                let user = response.json();
                if (user && user.token) {
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
  }

  logout() {
    localStorage.removeItem('currentUser');
  }
}

我将此服务注入我的登录组件并使用它:

import { ActivatedRoute, Router } from "@angular/router";
import { Component, OnInit } from '@angular/core';

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

@Component({
  selector: 'aa-login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
  model: any = {};
  loading = false;
  returnUrl: string;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private authenticationService: AuthenticationService,
              private alertService: AlertService) { }

  ngOnInit() {
    this.authenticationService.logout();
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

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

}

我的app.module看起来像这样:

import { BaseRequestOptions, HttpModule } from '@angular/http';
import { fakeBackendFactory, fakeBackendProvider } from './_helpers/mock-backend.service';

import { AlertComponent } from './_directives/alert.component';
import { AlertService } from './_services/alert.service';
import { AppComponent } from './app.component';
import { AuthGuard } from './_guards/auth.guard';
import { AuthenticationService } from './_services/authentication.service';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { MockBackend } from "@angular/http/testing";
import { NgModule } from '@angular/core';
import { RegisterComponent } from './register/register.component';
import { routing } from './app.routing';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent,
    RegisterComponent,
    AlertComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    routing,
    HttpModule
  ],
  providers: [AuthGuard, 
              AuthenticationService,
              AlertService,
              MockBackend,
              BaseRequestOptions,
              fakeBackendProvider],
  bootstrap: [AppComponent]
})
export class AppModule { }

所有内容都在模块中导入,并通过组件良好注入。不过,当我调用Authentication.service的登录功能时,我得到此错误

  

LoginComponent.html:3 ERROR TypeError:无法读取未定义的属性“post”       在AuthenticationService.webpackJsonp.86.AuthenticationService.login(authentication.service.ts:14)       在LoginComponent.webpackJsonp.88.LoginComponent.login(login.component.ts:28)       在Object.eval [as handleEvent](LoginComponent.html:3)       at handleEvent(core.es5.js:11826)       at callWithDebugContext(core.es5.js:13041)       at Object.debugHandleEvent [as handleEvent](core.es5.js:12629)       at dispatchEvent(core.es5.js:8777)       在core.es5.js:10654       在SafeSubscriber.schedulerFn [as _next](core.es5.js:3840)       在SafeSubscriber .__ tryOrUnsub(Subscriber.js:236)

我甚至尝试在authentication.service的构造函数中使用 @Inject(Http)private http 注入我的服务,但我遇到了同样的错误。我错过了什么?

0 个答案:

没有答案