Angular 2形式,get方法而不是帖子

时间:2017-07-26 10:21:00

标签: forms angular submit

在处理Angular 2表单时,我遇到了问题。当我在组件中创建一个对象时,一切都运行良好,我的表单通过post方法提交。但是,当我使用组件外部的类中的对象时,我的表单会发送带有URL http://localhost:4200/blog?title=sss&content=ssssss的获取请求

有谁知道为什么会这样?

模板:

 <form (ngSubmit)="onSubmit()" #f="ngForm">
   <!-- <form #f="ngForm" (ngSubmit)="onSubmit(f)">-->
      <div class="form-group">
        <label for="title">Tytuł</label>
        <textarea class="form-control" id="title" rows="1"
                  ngModel name = "title" required minlength="3" #title="ngModel"></textarea>
        <span class="help-block" *ngIf="!title.valid && title.touched">Wprowadzono za krótki tekst (minum to 3 znaki).</span>
        <label for="content">Zawartość:</label>
        <textarea class="form-control" id="content" rows="3"
                  ngModel name = "content" required minlength="3" #content="ngModel"></textarea>
        <span class="help-block" *ngIf="!content.valid && content.touched">Wprowadzono za krótki tekst (minum to 3 znaki).</span>
      </div>
      <button type="submit" class="btn btn-primary"
              [disabled] ="!f.valid"
      >Wyślij</button>
    </form>

组件:

import {Component, OnInit, ViewChild} from '@angular/core';
import {NgForm} from "@angular/forms";
import {Blog} from "../../shared/blog";
import {BlogService} from "../../services/blog.service";

@Component({
  selector: 'app-blog-form',
  templateUrl: './blog-form.component.html',
  styleUrls: ['./blog-form.component.css']
})
export class BlogFormComponent implements OnInit {

  @ViewChild('f') form: NgForm;
  errorMessage: string;
/* this works well
blog = {
    title: '',
    content: '',
    dateCreated: ''
  }*/

//this doesn't work
blog: Blog;

  ngOnInit(){}

  onSubmit(){
    this.blog.title = this.form.value.title;
    this.blog.content = this.form.value.content;
  }
}

Blog类。我试过这两个:

export class Blog {
  constructor(public title = '', public content = '', public dateCreated = ''){}}

而且:

export class Blog {
  constructor(public title : string, public content : string, public dateCreated : string){}}

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

我不确定为什么会这样,但请不要使用this.form.value

onSubmit(){
  this.blog.title = this.form.title;
  this.blog.content = this.form.content;
  console.log(this.blog);
}

使用超值发布回您的网页。现在这个代码应该可以工作。