I am developing a web app in angular, I already did the ApiRest and I tried it with Postman and good in theory (I'm not sure) all the code in angular is fine since it does not throw any errors, but the data I add from the form is not saved in the database, I mean that a new product appears on the base but emptied, on the other hand when I add products from Postman if everything is saved correctly.
This is the service code.
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/observable';
import { Producto } from '../models/producto';
import { GLOBAL } from './global';
@Injectable()
export class ProductoService{
public url: string;
constructor(
public _http : Http
){
this.url=GLOBAL.url;
}
getProductos(){
return this._http.get(this.url+'productos').map(res => res.json());
}
addProducto(producto: Producto){
let json = JSON.stringify(producto);
let params = 'json='+json;
let headers = new Headers({'Content-Type':'aplication/x-www-form-urlencoded'});
return this._http.post(this.url+'productos',params,{headers:headers})
.map(res => res.json());
}
}
The code of the component to add elements to the database
import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params} from '@angular/router';
import { ProductoService } from '../services/producto.service';
import { Producto } from '../models/producto';
@Component({
selector: 'producto-add',
templateUrl: '../views/producto-add.html',
providers: [ProductoService]
})
export class ProdcutoAddComponent{
public titulo: string;
public producto: Producto;
constructor(
private _productoService:ProductoService,
private _route: ActivatedRoute,
private _router: Router
){
this.titulo = 'Crear un nuevo producto';
this.producto = new Producto(0,'','',0,'');
}
ngOnInit(){
console.log('El componente de agregar un producto se ha cargado correctamente');
}
onSubmit(){
console.log(this.producto);
this._productoService.addProducto(this.producto).subscribe(
response =>{
if(response.code == 200){
this._router.navigate(['/productos-list']);
}else{
console.log(response);
}
},
error =>{
console.log(<any> error);
}
);
}
}