2017-04-03 48 views
0

我想发布有关Angular2的MEAN APP的数据我不知道为什么发送params数据为null,在控制台上唯一的价值是发送的是内容类型这是我的代码和控制台响应。Angular2不发布数据使用HTTP提供商

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 } 
+0

在'addApplicants'下应该是'this._http .post(this.base,body,options)' – Panther

回答

0

你传入PARAMS以错误的方式在服务端的响应HTTP POST方法是像

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

而且您发送类似的请求

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

谢谢我修正了通过这样的参数,但仍然得到这个响应这是结果----- {'{}':''} –

+0

这应该是其他一些逻辑问题 –