POST方法不记录输入信息

时间:2019-02-20 11:51:25

标签: javascript angular typescript

我创建了一个带有“ title”和“ body”的表单,并且计划是每当我在其中写入并提交内容时,都应在console.log中显示该表单。我尝试这样做,但这仅给了我这个:

  

{id:0,标题:“”,正文:“”,userId:0}

这是我的form-add.component.ts:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { form } from '../forms/form-interface';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-form-add',
  templateUrl: './form-add.component.html',
  styleUrls: ['./form-add.component.css']
})
export class FormAddComponent implements OnInit {
  private formUrl = "https://jsonplaceholder.typicode.com/posts";

  forms: form = {
    "id": 0,
    "userId": 0,
    "title": '',
    "body": ''
  };


  constructor(private http: HttpClient, private route: ActivatedRoute,
    private router: Router ) { }

  ngOnInit() {

  }

      addForm() {
        fetch(this.formUrl, {
          method: 'POST',
          body: JSON.stringify({
            id: this.forms.id,
            title: this.forms.title,
            body: this.forms.body,
            userId:  this.forms.userId
          }),
          headers: {
            "Content-type": "application/json; charset=UTF-8"
          }
        })
        .then(response => response.json())
        .then(json => console.log(json))
    }


  }

这是我的HTML代码:

<div class="container">
  <a class="btn btn-primary pull-right" routerLink = '/posts' >
    Back
    </a>
</div>

<div class="container">
  <h2>Add New Form:</h2>
</div>

<div class="forms container">
<form #postForm="ngForm">
    <div class="form-group">
        <label for="title">Title</label>
        <input  
        name="title"  
        id="title" 
        type="text" 
        class="form-control"
        >
    </div>
    <div class="form-group">
      <label for="body">Body</label>
      <textarea  
      name= "body" 
      id="body" 
      cols="30" 
      rows="10" 
      class="form-control"
      ></textarea>
    </div>
    <button class="btn btn-success" (click) = addForm()>Add</button>
</form>
</div>

这是我的表单界面:

export interface form  {
    "userId": number,
    "id": number,
    "title": string,
    "body": string
}

1 个答案:

答案 0 :(得分:0)

fetch(this.formUrl, {...})
    .then(response => response.json())
    .then(json => console.log(json))

这意味着:来自服务器的打印响应。服务器可以根据服务器的实现更改值或提供新的数据集。 如果您要打印请求,则可以在发送http请求之前完成它,例如:

console.log({ id: this.forms.id, body: this.forms.body })