Gabriel Sule
Gabriel Sule

Reputation: 383

Angular 2 HTTP post Web API 2 always receive null

user.service.ts

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

import * as myGlobal from '../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 I invoke method Insert, the data always arrive in null or zero, I had to change the { 'Accept' : 'application/json' } line for { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' : 'application/json' } because it gave me 405 error

Thanks in advance to everyone

Upvotes: 0

Views: 1337

Answers (2)

Ali Adravi
Ali Adravi

Reputation: 22823

Problem is here:

return this.http.post(myGlobal.myUrl + 'user/insert' 
     , JSON.stringify(user)
     , {headers: headers});

Change it 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 will need some import:

  import { Http, Response } from '@angular/http';
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/catch';
  import 'rxjs/add/observable/throw';

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68685

Change your input value to user , the passed data's name and the accepted parameter must be with same name. In postUser you get your data's name as user. Make the same in the API also.

[HttpPost]
[Route("api/user/insert")]
public HttpResponseMessage insertVehiclesDevice(modelUser user)
{
  //stuff
  return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

Upvotes: 0

Related Questions