【问题标题】:How to do POST in FORM Submit to angular2 and pass the object value into REST service?如何在 FORM 中进行 POST 提交到 angular2 并将对象值传递给 REST 服务?
【发布时间】:2016-08-25 02:23:31
【问题描述】:

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

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

这是我的项目结构:

这是我的 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());
  }

}

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

【问题讨论】:

  • subscribehttp.postobservable 触发请求。
  • 你能给我完整的代码吗? @HarryNinh
  • 不应该是 dataResponse 而不是 data 吗?而不是submitForm(data:Object){ this._restfull.saveRetur(data).subscribe((dataResponse) =&gt; { console.log("exec " + data); }); } 应该是submitForm(data:Object){ this._restfull.saveRetur(data).subscribe((dataResponse) =&gt; { console.log("exec " + dataResponse); }); }

标签: java json rest angular


【解决方案1】:

创建一个新的返回:

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

将其更改为:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 我刚刚像你说的那样更新了我的代码,但仍然没有工作,数据仍然得到 NULL 值,我错过了什么吗?
    • 好的,重新阅读问题后,我意识到它不是您看到的未定义的响应数据,而是来自组件文件的数据。此处的参数数据将为空,因为您没有向表单中的 submitForm 方法传递任何内容。您应该在函数中使用this.data 来访问绑定到表单中值的属性
    • 编辑我的答案以使用组件类的数据属性
    • 仍然无法正常工作,我刚刚用你的答案更新了我的代码,当我执行 console.log(this.data) 时数据“未定义”
    猜你喜欢
    • 2017-01-02
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2019-10-21
    相关资源
    最近更新 更多