typescript 属性“http”在类型“Component”上不存在,Angular 2

i5desfxk  于 2023-04-13  发布在  TypeScript
关注(0)|答案(5)|浏览(152)

我是angular2和typescript的新手,已经花了半天的时间来弄清楚ng 2表单。我已经完成了所有的路线,构建了所有必要的表单,目前正在尝试了解如何使用typescript在angular2中发布
这是我的错误:
Error in [default] 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 { }
0s0u357o

0s0u357o1#

只需添加private,使Http示例可用于整个组件:

constructor(private http: Http)
fkvaft9z

fkvaft9z2#

它与您的http变量有关,请尝试以下操作
在您的组件.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);
  }
6l7fqoea

6l7fqoea3#

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

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

xtfmy6hx4#

问题错误TS 2339:类型“FoodListComponent”上不存在属性“http”,已通过在构造函数构造函数中将http设为私有解决(私有http:Http){ this.http = http;}

ggazkfy8

ggazkfy85#

constructor(private http: HttpClient) {}

只需要使用dependency injection就可以了
HttpClient用于执行HTTP请求,它是从@angular/common/http导入的。HttpClient更现代,更易于使用HTTP的替代品。HttpClient是Http. src的改进替代品

相关问题