繁体   English   中英

Angular2不使用HTTP提供程序发布数据

[英]Angular2 not post data using HTTP providers

我正在尝试使用Angular2在MEAN APP上发布数据,我不知道为什么在null上发送params数据,在控制台上唯一要发送的是内容类型,这是我的代码和控制台响应。

home.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators, 
ReactiveFormsModule, FormsModule} from '@angular/forms';
import {ActivatedRoute, Router, CanDeactivate } from 
'@angular/router';

import { HomeService } from './home.service';
import { HOME } from './home';
import { BasicValidators } from '../shared/basicValidators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [HomeService, BasicValidators]
})
export class HomeComponent implements OnInit {
  public applicantForm: FormGroup;
  public submitted: boolean;
  responseStatus:Object= [];
  public applicants: HOME[]= [];
  public data: string;
  public _id: 0;
  public title: string;

  applicant: HOME = new HOME();
  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router, 
    private _hService: HomeService,
  ) { }

  private sub:any;

  ngOnInit() {
    this.getAll();
    this.initForm(); 
    // var _id = this.route.params.subscribe(params => {
    //     var _id = params['_id'];
    //     this.title = _id ? 'Edit Applicant' : 'New Applicant';

    //     if(!_id)
    //     return;

    //     this._hService.getApplicant(_id).subscribe(
    //         applicant => this.applicants = applicant,
    //         response => {
    //           if(response.status == 400){
    //             this.router.navigate(['Not Found'])
    //           }
    //         }
    //     )
    // });

    this.sub = this.route.params.subscribe(params => {
      this._id = params["id"];
    })
    if (this._id > 0) { 
            this.title = "Edit Material"
        } else {
            this.title = "Add Material"
        }

        if (!this._id) {
            return;
        }

        this._hService.getAllApplicants().subscribe(
          applicants => {
            this.applicants = applicants

            let Form = (this.applicantForm)
            if (this._id > 0) {
              (<FormGroup>this.applicantForm).setValue(applicants, { onlySelf: false});
            }
          }
      );

  }

  initForm() {
   this.applicantForm = this.formBuilder.group({
     workbefore: ['',  Validators.required],
     payrange: ['', Validators.required],
     desposition: ['', Validators.required],
     name: ['', Validators.required]
   })


  }

  getAll(){
     this._hService.getAllApplicants().subscribe(
        applicants => {
          this.applicants = applicants
          console.log(applicants)
        }
     )
  }

  submit(model:HOME) {
    this._hService.addApplicants(this.applicant).subscribe(


      err => console.log(err),
      () => {
        console.log('Applicacion Enviada Exitorsamente!!! ...');
        console.log(this.responseStatus = this.data)
        console.log(this.applicant)
      }
    )
  }

  // submit(model: HOME, isValid: boolean) {
  //   let result;
  //     this._hService.addApplicants(model).subscribe(
  //       applicant => {
  //         this.applicants = applicant;
  //       }
  //     )
  //   console.log('Applicacion Enviada Exitorsamente!!! ...');
  // }

}

home.service.ts

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

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable }  from 'rxjs/Observable';

import {HOME} from './home';

@Injectable() 
export class HomeService {

     private base: string = 'http://localhost:3000/applicants';
    constructor(
        private _http: Http,
    ) {}


    getAllApplicants(): Observable<any> {
        return this._http.get(this.base)
        .map(res => res.json())
        .catch(this.handleError);
    }

    getApplicant(_id) {
        return this._http.get(this.base +_id)
        .map(res => res.json())
        .catch(this.handleError);
    }

    addApplicants(applicant:any): Observable<HOME[]> {
        //let body = JSON.stringify(applicants);
        let body = new URLSearchParams(applicant);
        let headers = new Headers();
        let options = new RequestOptions({headers: headers});
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        return this._http.post(this.base , options, body )
        .map(res => res.json())
        .catch(this.handleError);
    }


    private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
    }

    private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
    }
}

home.component.html

 <form [formGroup]="applicantForm"  (ngSubmit)="submit()">
        <div class="row">
          <h3 class="form-padding">Applicant</h3>
          <div class="col-md-4">
            <div class="form-group">
              <label for="workbefore">Have you worked at MOTIVA before?</label>
               <select  name="" id="" class="form-control"  [(ngModel)]="applicants.workbefore" formControlName="workbefore" >
                  <option value="select">Select</option>
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
               </select>
              </div>

          </div>
          <div class="col-md-4">
              <div class="form-group">
                <label for="pay-range">Desire pay range?</label>
                <input  type="text" class="form-control" [(ngModel)]="applicants.payrange" formControlName="payrange"/>
              </div>
          </div>

           <div class="col-md-4">
              <div class="form-group">
                <label for="position">Desired Position</label>
                <select name="" id="" class="form-control" [(ngModel)]="applicants.desposition" formControlName="desposition">
                  <option value="">Select</option>
                  <option value="">Costumer Service Representative</option>
                  <option value="">Spanish Costumer Service</option>
                  <option value="">Claims Representative</option>
                  <option value="">Sales Executive</option>
                  <option value="">Other</option>
                </select>
              </div>
          </div>
        </div> 

这是home.ts模型

export class HOME {
_id?: string;
workbefore?: string;
payrange: string;
desposition: string;
name: string;
psourname: string;
msourname: string;
dob: Date;
age: number;
gender: string;
pofbirth: string;
nationality: string;
city: string;
state: string;
zipcode: number;
street: string;
streetNumber: string;
appartNumber: string;
homePhone: number;
mobileNumber: number;
secondaryPhone: string;
radio: string;
email: string;
relation: string;
spouseName: string;
childrens: string;
fatherName: string;
motherName: string;
emergencyContact: string;
relationshipContact: string;
relcontactPhone: string;
dependetYou: string;
timeResident: string;
education: string;
school: string;
graduationDate: string;
degree: string;
englishProficiency: string;
computerProficiency: string;
validVisa: string;
bodyTattos: string;
memberClub: string;
criminalRecord: string;
prisionMexico: string;
shift: string;
callWork: string;
nightShift: string;
refName: string;
refPhone: string;
refKnow: string;
refEmail: string;
workExperince: string;
companyName: string;
companyCountry: string;
companyDate: string;
leaveJob: string;
jobTitle: string;
supervisorName: string;

}

以下是终端的回复

{ method: null,
 headers: { 'Content-Type': [ 'application/x-www-form-urlencoded' ] },
 body: null,
 url: null,
 withCredentials: null,
  responseType: null }

您在服务中以错误的方式传递了参数,http post方法就像

this.http.post(url, body, options)

您正在发送类似的请求

return this._http.post(this.base , options, body )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM