简体   繁体   English

Angular 2控件的Post和Http响应

[英]Angular 2 control of Post and Http response

how can I create a post with Angular 2, I have my service.ts 如何使用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());
    }

and my createrestaurant.component 和我的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 这是回购

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. 错误可能是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());
}

If you want to send a query parameter please check. 如果要发送查询参数,请检查。 How to pass url arguments (query string) to a HTTP request on Angular? 如何将url参数(查询字符串)传递给Angular上的HTTP请求?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM