0

how can I create a post with Angular 2, I have my service.ts

addRestaurante(restaurante: Restaurante) {
    let json = JSON.stringify(restaurante);
        let params = "json="+json;
        let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
        return this._http.post(this.URL_API, params, {headers: headers}).map(res => res.json());
    }

and my createrestaurant.component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {Restaurante} from '../model/restaurante';
import {RestauranteServicio} from '../services/restaurantes.services';
@Component({
  selector: 'app-agregarestaurante',
  templateUrl: './agregarestaurante.component.html',
  styleUrls: ['./agregarestaurante.component.css'],
  providers: [RestauranteServicio]
})
export class AgregaRestauranteComponent implements OnInit {
  public titulo = 'Crea un Restaurante';
  public restaurante: Restaurante;
  public status: string;
  public unerror: string;
  constructor(
    private _restauranteServicio : RestauranteServicio,
    private route : ActivatedRoute,
    private router : Router
  ) { }
  ngOnInit() {
    this.restaurante = new Restaurante(0,"","","","null","bajo");
  }
  onSubmit() {
   this._restauranteServicio.addRestaurante(this.restaurante).subscribe(
  response => { 
    this.status = response.status;
    this.restaurante = response.data;
    if(this.status !== "success"){
      alert('error on server');
    }
    },
    error => {
      this.unerror = <any>error;
      if(this.unerror !== null) {
        console.log(this.unerror);
        alert('error en la peticion');
      }
    }
    );
    this.router.navigate(["/"]);
  }
}

at the time of doing submit returns "error on the server", which could be wrong in the code ? this is the repo

Gerardo Bautista
  • 795
  • 3
  • 11
  • 19

1 Answers1

0

Error could be params variable on service.ts because you are sending a string as body of request, please try to change it to a object.

addRestaurante(restaurante: Restaurante) {
  let json = JSON.stringify(restaurante);
  let params = {json: JSON.stringify(restaurante)};
  let headers = new Headers({'Content-Type':'application/x-www-form urlencoded'});
  return this._http.post(this.URL_API, params, {headers: headers}).map(res => res.json());
}

If you want to send a query parameter please check. How to pass url arguments (query string) to a HTTP request on Angular?

Luis Reinoso
  • 748
  • 4
  • 13