为什么(点击)在<button>内发送我的数据,但是(输入)在<input>内的(更改)在Angular,HTML中发送

时间:2019-06-26 18:10:18

标签: html angular typescript http

我想向我的Glassfish RESTful服务器发送一些数据。当我在输入标签中使用(更改)时,它会激活该方法并成功发送数据,但是当我使用(单击)或(更改)来激活该方法时,它不会执行任何操作。我试图将发送数据方法和路由器方法分开,但无济于事。  我该怎么解决?

html文件:

<div class="container py-5">
  <div class="row">
    <div class="col-md-12">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="card rounded-0">
            <div class="card-header">
              <h3 class="mb-0">Organize</h3>
            </div>
            <div class="form-group">
              <label for="codes" class="m-2">Choose a restaurant:</label>
              <form #f="ngForm">
                <input
                  type="text"
                  list="codes"
                  class="m-2"
                  (change)="saveCode($event)"
                  >
                <datalist id="codes">
                  <option *ngFor="let c of codeList" [value]="c.name">{{c.name}}</option>
                </datalist>
              <button
                type="button"
                class="btn btn-primary btn-lg float-none m-2"
                id="btnAanmaken"
                (click)="routerRed()"
              >Aanmaken</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

打字稿文件:


import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from "@angular/router";
import {NgForm} from "@angular/forms";
import {HttpClient, HttpHeaders} from "@angular/common/http";
@Component({
  selector: 'app-organize',
  templateUrl: './sendinvite.component.html',
  styleUrls: ['./sendinvite.component.css']
})
export class SendinviteComponent implements OnInit {

  // public codeValue: string;

  // List of restaurants
  codeList = [
    { name: 'Mcdonalds', address: 'Kalverstraat 5' },
    { name: 'Kentucky Fried Chicken', address: 'Kalverstraat 4' },
    { name: 'Burger King', address: 'Kalverstraat 3' },
    { name: 'Dominos pizza', address: 'Kalverstraat 2' },
    { name: 'New York Pizza', address: 'Kalverstraat 1' }
  ];

// Assign empty value to id, name and address
  @ViewChild('f', { static: true }) form: NgForm;


  restaurant = {
    name: ' ',
    address: ' '
  };

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      Authorization: 'my-auth-token'
    })
  };


  constructor(private http: HttpClient, private router: Router) {
  }

  ngOnInit() {
  }

// Method to post data to backend
  public saveCode (e): void {
    const name = e.target.value;
    const list = this.codeList.filter(x => x.name === name)[0];


    this.restaurant.name = list.name;
    this.restaurant.address = list.address;

    console.log(list.name);
    console.log(list.address);


// Additional information to the server content type
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
      })
    };
// Making an array with the values of the restaurant
    const data = {
      name: list.name,
      address: list.address
    };

    console.log(data);

// POST method
    this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant',
      JSON.parse(JSON.stringify(data)) , httpOptions)

    // wait till it gets posted to the backend
      .subscribe( // subscribe to observable http.post
        res => {
          console.log("response" + " " + res); // log results otherwise log error
        },
        err => {
          console.log('Error occured');
        }

      );


  }

  routerRed(){
    this.router.navigateByUrl('/menu');
  }



我尝试使用:

<button 
                type="submit" 
                class="btn btn-primary btn-lg float-none m-2" 
                id="btnAanmaken"
                routerLink="/menu"
                (change)="saveCode($event)"
                >Aanmaken</button>

和:

<button 
                type="submit" 
                class="btn btn-primary btn-lg float-none m-2" 
                id="btnAanmaken"
                routerLink="/menu"
                (click)="saveCode($event)"
                >Aanmaken</button>

2 个答案:

答案 0 :(得分:0)

按钮内的(change)事件将什么都不做,(click)更合适,但是click事件中传递的$event将返回有关点击的信息本身(鼠标位置等)。

您应该做的是,每当单击click时,获取表单的值并将其发送到saveData函数。 (也许通过做类似saveData(this.f.value)的操作,但我不能肯定地说出来)

我没有使用模板驱动的表单的经验,也许值得您看看Reactive Forms,它会让您的生活更轻松恕我直言

答案 1 :(得分:0)

单击//addClass on focus $("input[type='text']").focus(function(){ $(this).closest('div, td').addClass("focusActive"); }); //removeClass on blur $("input[type='text']").blur(function() { if(!$(this).val()) { $(this).closest('div, td').removeClass("focusActive"); } }); //button click to removeClass $("#post_btn").click(function(){ setTimeout( function() { if(!$("#locationField input[type='text']").val() ) { $("#locationField").removeClass("focusActive"); } }, 400); }); 事件将不会在单击按钮时触发,因为这样就没有“更改”。您应该改用(change)。同时设置(click)saveCode()时未调用routerLink的原因是由于(click)。当您单击按钮时,Angular在导航到routerLink之前会触发您的点击事件。您可以改为从/menu中的组件进行导航。

由于您的saveCode()中也有一个API调用,因此如果您成功导航,可能会更好,因为如果API调用失败(特别是如果新的API调用失败,则重新路由用户可能没有意义)路线取决于保存的数据)

在您的代码中尝试一下。

HTML

saveCode()

组件

<button type="submit"
  class="btn btn-primary btn-lg float-none m-2"
  id="btnAanmaken"
  (click)="saveCode($event)">
  Aanmaken
</button>

编辑:您可以使用代码中使用的.subscribe( // subscribe to observable http.post res => { console.log("response" + " " + res); // log results otherwise log error this.router.navigateByUrl('/menu'); }, err => { console.log('Error occured'); }); 和ngModel,而不必使用$event将值传递给组件。 / p>

组件

ngForm

组件

<input type="text"
  list="codes"
  class="m-2"
  name="restaurantName"
  ngModel
>

这是documentation中的另一个示例,该示例说明了如何使用ngForm和ngModel将值绑定到表单上