如何在FORM中进行POST提交到angular2并将对象值传递给REST服务?

时间:2016-08-25 02:23:31

标签: java json rest angular

我想要实现的是我想将整个表单值发布到我的RESTfull服务中,但是我对在angular2中使用表单以及如何在提交表单时传递和检查对象值感到困惑?

它不会触发我的Restful服务,并且它不会给我一个错误,我想我错过了一些东西,下面是我如何做的

这是我的项目结构: enter image description here

这是我的app.component.html:

Create a new Retur: 
<form (ngSubmit)="submitForm()"> 

      <div class="form-group">
        <label for="nomor_transaksi">Nomor Transaksi</label>
        <input type="text" placeholder="nomor transaksi" [(ngModel)]="data.nomor_transaksi" [ngModelOptions]="{standalone: true}"/>
      </div>

      <button type="submit">Save Contact</button>

</form>
下面的

是我的app.component.ts:

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from './navbar';
import { RestfullService } from './restfull.service';
import { Observable } from 'rxjs/Rx';
import { HTTP_PROVIDERS, HTTP_BINDINGS, Http, Response, HttpModule} from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [NavbarComponent],
  providers: [RestfullService, HTTP_PROVIDERS]
})

export class AppComponent {
  title = 'app works!';
  public data;
  public active;

  ngOnInit(){
    this.getRest();
  }

  constructor(private _restfull: RestfullService) {
    this.data = { nomor_transaksi: '12345678' }
   }

  getRest(){
    this._restfull.getDashboard().subscribe(
      data => {this.active = data[0]}
    );
  }

  submitForm(data:Object){
    this._restfull.saveRetur(data);
    console.log("exec" + data);
  }
}

在这种情况下,我的POST函数是submitForm(),它是访问restfull.service.ts类,下面是restfull.service.ts类:

    import { Injectable } from '@angular/core';
    import { HTTP_PROVIDERS, HTTP_BINDINGS, Http, Response, HttpModule} from '@angular/http';
    import { Observable } from 'rxjs/Rx';

    @Injectable()
    export class RestfullService {

      constructor(private http:Http) { }

      getDashboard(){
        return Observable.forkJoin(
        this.http.get('http://localhost:8080/springserviceweb/').map((res:Response) => res.json())
        );
      }

      saveRetur(data){
        this.http.post('http://localhost:8080/springserviceweb/service/save', JSON.stringify(data))

  }

}

以下是我的RESTfull服务如何检索数据:

// save
@RequestMapping(value = "/save", method = RequestMethod.POST, consumes ="application/json")
  public ReturHeader save(@RequestBody ReturHeader Retur, UriComponentsBuilder ucBuilder) throws Exception {

    try {
        Retur.setNomor_Transaksi(retur.generateAutoNomorRetur());
        retur.saveRetur(Retur);

    } catch (Exception e) {
         Retur.setERROR_STAT(e.getMessage().trim());
        // return new ResponseEntity<ReturHeader>(Retur,HttpStatus.NOT_FOUND);
    }

    return Retur;
}

我的服务应该检索一个对象,如何正确地使用angular2将JSON对象从HTML传递到我的服务?当我尝试我的代码时,它只显示我的数据属性未定义

更新了我的代码: 这是我的app.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from './navbar';
import { RestfullService } from './restfull.service';
import { Observable } from 'rxjs/Rx';
import { HTTP_PROVIDERS, HTTP_BINDINGS, Http, Response, HttpModule} from '@angular/http';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [NavbarComponent],
  providers: [RestfullService, HTTP_PROVIDERS]
})

export class AppComponent {
  title = 'app works!';
  public data;
  public active;
  datareturForm: FormGroup;

  constructor(private _restfull: RestfullService, private formBuilder: FormBuilder) {
    this.data = { nomor_transaksi: '12345678' }
   }

  ngOnInit(){
    this.getRest();

    this.datareturForm = this.formBuilder.group({
      "nomor_transaksi": ['', Validators.maxLength(10)]
      //nomor_transaksi: ['', Validators.maxLength(10)]
    })
  }

  getRest(){
    this._restfull.getDashboard().subscribe(
      data => {this.active = data[0]}
    );
  }

  submitForm(data:Object){
    this._restfull.saveRetur(data).subscribe((dataResponse) => {
      console.log("exec " + data);
    });

  }
}

在我的resful.service.ts下面:

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

@Injectable()
export class RestfullService {

  constructor(private http:Http) { }

  getDashboard(){
    return Observable.forkJoin(
    this.http.get('http://localhost:8080/springserviceweb/service/retur/getwil/OTLB001/JKT').map((res:Response) => res.json())
    );
  }

  saveRetur(data){
    console.log('masuk ke service');
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    let body = JSON.stringify(data);
    return this.http.post('http://localhost:8080/springserviceweb/service/retur/save', data, headers).map((res:Response) => res.json());
  }

}

仍然是“数据”变量是UNDEFINED,当发送到我的RESTfull服务时,我在这里错过了什么?

2 个答案:

答案 0 :(得分:1)

  

创建一个新的返回:

<form (ngSubmit)="submitForm()">

将其更改为:

<form (ngSubmit)="submitForm(form)" #form="ngForm">

答案 1 :(得分:0)

您的observable未运行,因为您没有订阅它将返回的结果,这就是console.log返回undefined的原因。要解决此问题,请将app.component.ts中的代码更改为以下内容:

submitForm() {
    this._restfull.saveRetur(this.data)
        .subscribe((dataResponse) => {
            console.log("exec" + this.data);
        });
}

这可以解决您遇到的问题。

编辑:更改了答案 - 问题不是关于可观察不运行 - 虽然这仍然是原始代码中的问题,但实际上是一个未定义参数的问题,而应该是对类变量的引用。