c# - Angular 2 HTTP post Web API 2 always receive null -
user.service.ts
import { injectable } '@angular/core'; import { http, response, headers } '@angular/http'; import 'rxjs/rx'; import { observable } 'rxjs/observable'; import * myglobal '../global'; @injectable() export class userservice { constructor(private http: http) {} postuser(user:any[]) { let headers = new headers({ 'content-type': 'application/x-www-form- urlencoded; charset=utf-8', 'accept' : 'application/json' }); return this.http.post(myglobal.myurl + 'user/insert', json.stringify(user) , {headers: headers}); } }
user.component.ts
submitform(data: any):void{ console.log(data); this._service.postuser(data) .subscribe( (response) => console.log(response), (error) => console.log(error) ); }
web api
[httppost] [route("api/user/insert")] public httpresponsemessage insertvehiclesdevice(modeluser data) { //stuff return new httpresponsemessage { statuscode = httpstatuscode.ok }; }
when invoke method insert, data arrive in null or zero, had change { 'accept' : 'application/json' }
line { 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', 'accept' : 'application/json' }
because gave me 405 error
thanks in advance everyone
problem here:
return this.http.post(myglobal.myurl + 'user/insert' , json.stringify(user) , {headers: headers});
change to:
return this.http.post(myglobal.myurl + 'user/insert' , json.stringify(user) , {headers: headers}) .map( (response: response) =>response.json()) .catch(this._errorhandler);
error handler:
_errorhandler(error:response){ console.log(error); return observable.throw(error || "internal server error"); }
you need import:
import { http, response } '@angular/http'; import { observable } 'rxjs/observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw';
Comments
Post a Comment