15

I'm new in angular2 and typescript and already spent a half day to figure out with ng2 forms. I have finished all my routes and builded all necessary form and currently trying to understand how to post in angular2 with typescript

This my error:

ERROR in [default] simpleapp/src/app/clients/add-client/add-client.component.ts:52:16 Property 'http' does not exist on type 'AddClientComponent'.

And I cannot find where is this problem coming from. I've imported angular/http in my component, I have provided header and response as oficial tutorial says but still can see this problem. What am I missing and where is my problem? thanks in advance

This is my component:

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);

  }
}

This is my template:

    <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>

This is my module:

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 { }
Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
antonyboom
  • 1,161
  • 2
  • 17
  • 44

5 Answers5

37

Just add private to make your Http instance available to your entire component:

constructor(private http: Http)
Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
  • 1
    @antonyboom Glad I could help. There are really good answers on the following links, I don't think I could give you better explanation than any of them: http://stackoverflow.com/questions/36147890/angular2-what-is-different-between-the-variable-declaring-in-the-class-and and http://stackoverflow.com/questions/34574167/angular2-should-private-variables-be-accessible-in-the-template – Stefan Svrkota Oct 04 '16 at 21:45
1

It has something to do with your http variable try this

In your component.ts

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

You could try

constructor(private http: Http) {
    http.get('api/departments')
      .map((res: Response) => res.json())
      .subscribe((departments: Array<any>) => this.departments = departments);
  }
Logan H
  • 3,383
  • 2
  • 33
  • 50
0

You have to export the Http module in the module in the exports declaration.

@NgModule({
  imports: [CommonModule, RouterModule, ReactiveFormsModule, ],
  declarations: [ ErrorMessagesComponent, FoodDashboardComponent ],
  exports: [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule, ]
})
John Baird
  • 2,606
  • 1
  • 14
  • 33
0

Issue error TS2339: Property 'http' does not exist on type 'FoodListComponent' solved by making http as private in constructor constructor(private http: Http) { this.http = http; }

Seema As
  • 90
  • 1
  • 2
0
constructor(private http: HttpClient) {}

just use dependency injection so you can use it

The HttpClient is used to perform HTTP requests and it imported form @angular/common/http. The HttpClient is more modern and easy to use the alternative of HTTP. HttpClient is an improved replacement for Http. src

ibrahimgb
  • 693
  • 5
  • 13
  • 1
    Please, don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. How is this better than the accepted answer? Is there a reason you're using `HttpClient` instead of `Http`? Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Zsolt Meszaros Apr 11 '23 at 08:01
  • 1
    that what worked for me, as i head the same problem, thought to share it. and HttpClient is used to perform HTTP requests and it imported form @angular/common/http. The HttpClient is more modern and easy to use the alternative of HTTP. HttpClient is an improved replacement for Http. – ibrahimgb Apr 11 '23 at 21:23