如何使用Angular 2创建帖子,我有 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());
}
和我的 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(["/"]);
}
}
在提交时返回“服务器错误”,这在代码中可能是错误的?这是repo
答案 0 :(得分:0)
错误可能是 service.ts 上的params变量,因为您将字符串作为请求正文发送,请尝试将其更改为对象。
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());
}
如果要发送查询参数,请检查。 How to pass url arguments (query string) to a HTTP request on Angular?