没有 Http 的提供者。区域 angular。任务承诺然后价值

No provider for Http. Zone angular. Task Promise then Value

我正在尝试从我的 Angular2 class 调用 Web API。

service.ts:

import { Component, OnInit, Injectable } from '@angular/core';
import { Http, RequestOptions, Headers  } from "@angular/http";
import { apimodel } from '../../_model/APImodel';
import Global = require('../../_utilities/constants/constants');
import { UserModel } from '../../_model/usermodel';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class services
{
    constructor(private http: Http){ }

    getLogin(model : UserModel)  {
        let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(Global.BASE_URL + '/login', model, options)
                .toPromise().then(res=><apimodel>res.json()).catch(this.handleError);
    }

    private handleError(error:any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.log("Error");
        console.error(error); // log to console instead
        return Promise.reject(errMsg);
    }
}

login.ts:

import { Component, OnInit } from '@angular/core';
import { UserModel } from '../../_model/usermodel';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import Global = require('../../_utilities/constants/constants');
import {apimodel} from "../../_model/APImodel";
import { services } from '../../_utilities/services/services';


@Component({
    templateUrl: './_componant/login/login.html'
})

export class LoginComponent implements OnInit{
    model : UserModel = {id : 0, email : "", password : "", username : ""};
    myform : FormGroup;
    submitted : boolean = false;
    returnUrl : string;
    response : apimodel;

    constructor( private route: ActivatedRoute, private router: Router, private services : services){

    }
    ngOnInit(): void {
        this.myform = new FormGroup({
            username : new FormControl("", Validators.required),
            password : new FormControl("", Validators.required)
        })

        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    login(model : UserModel){
        this.submitted = true;
        if(this.myform.valid)
        {
            this.services.getLogin(model).then(result => console.log(result)).catch(error => console.log(error));
            //Call Web Service to login
            console.log(this.returnUrl);
            this.router.navigate([this.returnUrl]);
        }
    };
}

Module.ts:

import { NgModule, PipeTransform }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule  } from '@angular/forms';
import { AppComponent } from './_componant/app/app.component';
import { appRouterModule } from './app.route';
import { LoginComponent } from './_componant/login/login';
import { RegistrationComponent } from './_componant/registration/registration';
import { services } from './_utilities/services/services';



@NgModule({
  imports: [BrowserModule, ReactiveFormsModule ,appRouterModule],
  declarations: [AppComponent, LoginComponent, RegistrationComponent],
  bootstrap:    [AppComponent],
  providers: [services]
})

export class AppModule { }

如您所见,我已正确注入服务 class 并在 service.ts

中正确添加 Http

我在控制台中收到以下错误:

您的 module.ts 文件中没有包含 HttpModule。

import { NgModule, PipeTransform }      from '@angular/core';
import { HttpModule  } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule  } from '@angular/forms';
import { AppComponent } from './_componant/app/app.component';
import { appRouterModule } from './app.route';
import { LoginComponent } from './_componant/login/login';
import { RegistrationComponent } from './_componant/registration/registration';
import { services } from './_utilities/services/services';

@NgModule({
  imports: [BrowserModule, ReactiveFormsModule, HttpModule, appRouterModule],
  declarations: [AppComponent, LoginComponent, RegistrationComponent],
  bootstrap:    [AppComponent],
  providers: [services]
})

export class AppModule { }

You have missed

import { HttpModule } from '@angular/http';

And

imports: [BrowserModule, ReactiveFormsModule, HttpModule, appRouterModule],

您需要像下面那样在 app.module

中导入 HttpModule

import { HttpModule } from "@angular/http";

然后在imports部分使用它

imports: [BrowserModule, ReactiveFormsModule ,appRouterModule,HttpModule]

但是,如果您正在使用 Angular 4 并且想要使用新的 HttpClientModule,它将在 angular 的更高版本中使用,那么您可以像下面那样使用它

在您的 app.module 中进行以下更改

import { NgModule, PipeTransform }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule  } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http;  //import the module here
import { AppComponent } from './_componant/app/app.component';
import { appRouterModule } from './app.route';
import { LoginComponent } from './_componant/login/login';
import { RegistrationComponent } from './_componant/registration/registration';
import { services } from './_utilities/services/services';


@NgModule({
  imports: [BrowserModule, ReactiveFormsModule ,appRouterModule,HttpClientModule],
  declarations: [AppComponent, LoginComponent, RegistrationComponent],
  bootstrap:    [AppComponent],
  providers: [services]
})

export class AppModule { }

在您的 service.ts class 中导入并注入,如下所示

import { HttpClient,HttpHeaders } from '@angular/common/http';

@Injectable()
export class services
{
    constructor(private http: HttpClient){ }
  /// rest of the code 
}