【问题标题】:Property 'http' does not exist on type 'Component', Angular 2Angular 2 类型“组件”上不存在属性“http”
【发布时间】:2026-02-03 14:10:01
【问题描述】:

我是 angular2 和 typescript 的新手,已经花了半天时间来弄清楚 ng2 表单。我已经完成了所有路线并建立了所有必要的表格,目前正在尝试了解如何使用打字稿在 angular2 中发布

这是我的错误:

[默认]中的错误 simpleapp/src/app/clients/add-client/add-client.component.ts:52:16 类型“AddClientComponent”上不存在属性“http”。

我找不到这个问题来自哪里。我已经在我的组件中导入了angular/http,我已经提供了官方教程所说的标题和响应,但仍然可以看到这个问题。我错过了什么,我的问题在哪里?提前致谢

这是我的组件

import 'rxjs/add/operator/map';

import {Component} from '@angular/core';
import {Http, Response, RequestOptions, Headers} from '@angular/http';

import {Employee} from "./model/add-client.model";

@Component({
  selector: 'app-add-client',
  templateUrl: 'add-client.component.html',
  styleUrls: ['add-client.component.css']
})

export class AddClientComponent {

   departments: Array<any>;
   firstName: '';
   lastName: '';
   id: null;
   salary: null;
   phone: null;
   departmentId: null;

  constructor(http: Http) {
    http.get('api/departments')
      .map((res: Response) => res.json())
      .subscribe((departments: Array<any>) => this.departments = departments);
  }

  model = new Employee(
    this.id,
    this.firstName,
    this.lastName,
    this.salary,
    this.departmentId,
    this.phone
  );

  submitted = false;

  addEmployee = 'api/employees'

  handleError = 'Post Error';

  onSubmit(model) {
    this.submitted = true;

    let body = JSON.stringify({ model });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.addEmployee, body, options)
      .catch(this.handleError);

  }
}

这是我的模板

    <div class="container">
    <md-card class="demo-card demo-basic">
      <md-card-title color="primary back-header">Employee Form</md-card-title>
      <md-card-content>
        <form (ngSubmit)="onSubmit(model)" #employeeForm="ngForm">
          <md-toolbar for="firstName">First Name</md-toolbar>
          <md-input
            class="demo-full-width input-text"
            type="text"
            id="firstName"
            required
            [(ngModel)]="model.firstName"
            name="firstName"
            #firstName="ngModel">
          </md-input>

          <md-toolbar for="lastName">Last Name</md-toolbar>
          <md-input
            class="demo-full-width input-text"
            type="text"
            id="lastName"
            required
            [(ngModel)]="model.lastName"
            name="lastName"
            #lastName="ngModel">
          </md-input>

          <md-toolbar for="salary">Salary</md-toolbar>
          <md-input
            class="demo-full-width input-text"
            type="number"
            id="salary"
            placeholder="USD"
            required
            [(ngModel)]="model.salary"
            name="salary"
            #salary="ngModel">
          </md-input>

          <md-toolbar for="departmentId">Department</md-toolbar>
            <select class="demo-full-width option-department input-text"
                    id="departmentId"
                    required
                    [(ngModel)]="model.departmentId"
                    name="departmentId"
                    #departmentId="ngModel">
              <option
                *ngFor="let department of departments"
                [value]="department.id">{{department.name}}
              </option>
            </select>

          <md-toolbar for="phone">Phone</md-toolbar>
          <md-input
            class="demo-full-width input-text"
            type="number"
            id="phone"
            placeholder="phone #"
            required
            [(ngModel)]="model.phone"
            name="phone"
            #phone="ngModel">
          </md-input>

          <button  md-raised-button color="primary"
                   type="submit"
                   class="btn btn-default"
                   [disabled]="!employeeForm.form.valid">Submit
          </button>
        </form>
      </md-card-content>
    </md-card>
  <md-card [hidden]="!submitted">
      <md-card-title>You submitted the following:</md-card-title>
    <md-list>
      <md-list-item>
        <label>First Name:</label> {{model.firstName}}
      </md-list-item>
      <md-list-item>
        <label>Last Name:</label> {{model.lastName}}
      </md-list-item>
      <md-list-item>
        <label>Salary:</label> {{model.salary}}
      </md-list-item>
      <md-list-item>
        <label>Department:</label> {{model.departmentId}}
      </md-list-item>
      <md-list-item>
        <label>Phone:</label> {{model.phone}}
      </md-list-item>
    </md-list>
  </md-card>
</div>

这是我的模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule }    from '@angular/http';


import { MaterialModule } from '@angular/material';
import {MdListModule} from '@angular/material/list';


import { AppComponent } from './app.component';
import { routing, appRoutingProviders }  from './app.routing';

//==============

import { ClientsComponent } from './clients/clients.component';
import { DepartmentsComponent } from './departments/departments.component';
import { AddClientComponent } from './clients/add-client/add-client.component';
import { AddDepartmentComponent } from './departments/add-department/add-department.component';

@NgModule({

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,

    MaterialModule.forRoot(),
    MdListModule.forRoot()
  ],

  declarations: [
    AppComponent,
    ClientsComponent,
    DepartmentsComponent,
    AddClientComponent,
    AddDepartmentComponent
  ],

  providers: [appRoutingProviders],

  bootstrap: [AppComponent]
})
export class AppModule { }

【问题讨论】:

    标签: forms angular typescript angular2-http


    【解决方案1】:

    只需添加 private 即可使您的 Http 实例可用于您的整个组件:

    constructor(private http: Http)
    

    【讨论】:

    【解决方案2】:

    这与您的 http 变量有关,试试这个

    在你的 component.ts 中

    constructor(http: Http) {
        http.get('api/departments')
          .map((res: Response) => res.json())
          .subscribe((departments: Array<any>) => this.departments = departments);
      }
    

    你可以试试

    constructor(private http: Http) {
        http.get('api/departments')
          .map((res: Response) => res.json())
          .subscribe((departments: Array<any>) => this.departments = departments);
      }
    

    【讨论】:

    • http 对于构造函数是本地的。
    【解决方案3】:

    你必须在exports声明的模块中导出Http模块。

    @NgModule({
      imports: [CommonModule, RouterModule, ReactiveFormsModule, ],
      declarations: [ ErrorMessagesComponent, FoodDashboardComponent ],
      exports: [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule, ]
    })
    

    【讨论】:

      【解决方案4】:

      问题错误 TS2339: 属性 'http' 在类型 'FoodListComponent' 上不存在通过在构造函数构造函数中将 http 设为私有来解决(私有 http: Http){ 这个.http = http; }

      【讨论】: