Angular2 Reactive Form Post HTTP

时间:2017-06-05 03:32:10

标签: api angular

我是使用angular2的新手。我只是不知道如何发送http表格。我使用反应形式。

这是我的HTML

<form novalidate [formGroup]="form" (ngSubmit)="onSubmit(form)"> 
  <div class="form-group">
    <input formControlName="categoryname" type="text" class="form-control" placeholder="Category" >
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<p>Form: {{ form.value | json }}</p>
<p>Form status: {{ form.status }}</p>
<p> {{error}}</p>

这是我的组件

import { Component } from '@angular/core';
import {Category} from './category';
import {CategoryService} from '../service/category.service';
import {FormBuilder, FormGroup, FormControl} from '@angular/forms';
import {Subscription} from 'rxjs';
import { ActivatedRoute, Params} from '@angular/router';

@Component({
    selector: 'registration',
    templateUrl:'./registration.html',
    styleUrls:['./registration.css'],
    providers: [CategoryService]
})

export class AppRegistration {

    categoryname: any;
    response: string;

    form: FormGroup;
    constructor(private categoryserv: CategoryService, public fb: FormBuilder) {
        this.form = this.fb.group({
            categoryname: '',
        });
    }

    onSubmit() {
        console.log(this.form.value, this.form.valid);
    }
}

这是我的服务

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';


import {Category} from '../app-registration/category';



@Injectable()
export class CategoryService {
    private urlcategory = "http://localhost:8080/create-category";
    constructor(private http: Http){ }

}

这是我的类别模型

export class Category {
   categoryname: string;
   constructor() { 
   }
} 

我的服务代码尚未完成。是的,因为那是我的问题。 如何制作服务代码并获取表单的价值,并根据我的模型类别代码发送到API链接。

我已经困惑了三天,我还没有得到任何答案。请帮帮我们:(

1 个答案:

答案 0 :(得分:1)

在您的服务中,为包含要传递的值的正文的http帖子生成函数

 @Injectable()
    export class CategoryService {
        private urlcategory = "http://localhost:8080/create-category";
        constructor(private http: Http){
       senddata(data : any)
         var body = JSON.stringify(data);
                var headers = new Headers();
                headers.append('Content-Type', 'application/json');
                return this.http.post(this.urlcategory, body, { headers: headers }).map((data: Response) => data.json()).catch(this.handleError);
     }

    }

在您的组件中调用服务并传递表单数据

 onSubmit() {
            this.categoryserv.senddata(this.form.value.categoryname).subscribe(data=>{
       console.log(data);
    })
        }