Namindu Sanchila
Namindu Sanchila

Reputation: 414

Postman 'POST' request sucess but Angular 5 'Post' not working

I am trying to insert a data object via web API to the database. when I using the Postmen, POST request is the success. but in angular 5 app post request indicates 500 Internal saver error. here is my source code.

player.service.ts

@Injectable()
export class PlayerService {


  private _postPlayer = 'http://192.168.8.101/api/Values/insertData';
  constructor(private _http: HttpClient) { }
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',

    })
  };

  // save the new player

  save(palyer: Player): Observable<Player> {

    console.log(palyer.playingRole);
    return this._http.post<Player>(this._postPlayer, palyer, this.httpOptions)
  }
}

here are my Components

export class AddplayerComponent implements OnInit {
 player: Player = new Player(); 
 playerAdd: FormGroup;
 players: Player[];

  constructor(private plService: PlayerService) { }

  ngOnInit() {
    this.playerAdd = new FormGroup(
     {
      firstName: new FormControl(),
      lastName: new FormControl(),
      nickName: new FormControl(),
      birthday: new FormControl(),
      playingRole: new FormControl(),
      battingStyle: new FormControl(),
      bowllingStyle: new FormControl(),
      mobileNumber: new FormControl(),
      email: new FormControl() 


     }

    );


  }

  save() {
    console.log(this.playerAdd.value);
   this.player = this.playerAdd.value;
   this.plService.save(this.player)
   .subscribe();
  }

}

Here are my ASP.NET WebApi Post

[HttpPost]
public void insertData([FormBody] Player Ob){
  // to connect EF6 context

}

Get request is working fine. but Post request is not working.

Upvotes: 0

Views: 863

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222522

You need to stringify your object:

  return this._http.post<Player>(this._postPlayer, JSON.stringify(palyer), this.httpOptions)

And added the microsoft.aspnet.webapi.cors package to the API.

Upvotes: 1

Namindu Sanchila
Namindu Sanchila

Reputation: 414

The error was I got here is not adding to the microsoft.aspnet.webapi.cors package to the API. just added it and its working fine. Thanks all for the support me.

Upvotes: 0

Related Questions