2017-07-26 67 views
0

在Angular 2表單提交時,遇到問題。當我在組件中創建一個對象時,一切正常,我的表單通過post方法提交。但是,當我使用組件外的類中的對象時,我的表單使用url發送獲取請求http://localhost:4200/blog?title=sss&content=ssssssAngular 2 form,獲取方法is post

有沒有人知道爲什麼會發生這種情況?

模板:

<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; 
    } 
} 

博客類中。我都嘗試這樣的:

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

這:

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

感謝所有幫助:)

+0

你能提供你創建的服務嗎? –

+0

我沒有使用該服務。這只是舊的進口 – angie

+0

問題仍然存在,如果我刪除導入 – angie

回答

0

我不知道爲什麼會這樣,但儘量不要使用this.form.value

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

使用有價值的帖子支持您的頁面。現在這個代碼應該工作。

+0

我得到一個錯誤比:屬性'標題'不存在類型'NgForm' – angie