Angular2帖子表格

时间:2017-06-09 03:48:38

标签: angular angular-routing

我是使用angular2框架的新手。我有一个表单,如果提交,它将数据传输到API。传递功能正常工作。然后是表格。点击提交后,表单上没有任何变化。我输入的数据仍在那里。我想如果我提交了表格,它可以改为直接转到另一个组件。

这是我的代码组件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';


import {CustomerService} from '../services/customer.service';



@Component({
  selector: 'app-app-register',
  templateUrl: './app-register.component.html',
  styleUrls: ['./app-register.component.css'],
  providers:[CustomerService]
})
export class AppRegisterComponent implements OnInit {

  register: FormGroup;
  loading = false;
  error = '';

  constructor(
    private fb: FormBuilder, 
    private service: CustomerService,
    private router: Router
    ) {}

  ngOnInit() {
    this.register = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      government: ['', [Validators.required, Validators.minLength(2)]],
      address: ['', [Validators.required, Validators.minLength(2)]],
      email: ['', [Validators.required, Validators.minLength(2)]],
      phone: ['', [Validators.required, Validators.minLength(2)]],
    });
  }

    onSubmit() {
    this.service.registerCustomer(this.register.value).subscribe(
      result => {
          if (result === true) {
              this.router.navigate(['/']);
          } else {
              this.error = 'data is incorrect';
              this.loading = false;
          }
      }, 
      error => {
        this.loading = false;
        this.error = error;
      });
  }

}

如果你需要,这是我的服务

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import {RegisterData} from '../model/model-register';

@Injectable()
export class CustomerService {

  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http: Http) { }

  registerCustomer( registerdata:RegisterData) : Observable<any>{
    return this.http.post("http://localhost:8080/customer/new", JSON.stringify(registerdata), {headers: this.headers})
    .map((res: Response) => res.json())
    .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }


  }

感谢帮助人们:)

0 个答案:

没有答案