加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular2中将表单提交到服务器?

发布时间:2020-12-17 07:06:03 所属栏目:安全 来源:网络整理
导读:现在提交已被angular2捕获,即使在 form中有action =. 演示链接:http://plnkr.co/edit/4wpTwN0iCPeublhNumT5?p=preview //our root app componentimport {Component} from 'angular2/core'@Component({ selector: 'my-app',providers: [],template: ` div h2
现在提交已被angular2捕获,即使在< form>中有action =.

演示链接:http://plnkr.co/edit/4wpTwN0iCPeublhNumT5?p=preview

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',providers: [],template: `
    <div>
      <h2>Hello {{name}}</h2>
      <form action="https://www.google.com" target="_blank" method="POST">
        <input name="q" value="test">
        <button type="submit">Search</button>
      </form>
    </div>
  `,directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

解决方法

您应该利用NgSubmit指令,如下所述:

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  (...)
  <input type="text" [(ngModel)]="data.name"/>
  (...)
  <button type="submit">Send</button>
</form>

在这种情况下,当您单击提交按钮时,将调用组件的onSubmit方法,您将能够使用Angular2上的HTTP类手动将数据发送到服务器:

@Component({
})
export class MyComponent {
  constructor(private http:Http) {
    this.data = {
      name: 'some name'
      (...)
    };
  }

  onSubmit() {
    this.http.post('http://someurl',JSON.stringify(this.data))
        .subscribe(...);
  }
}

这样您就可以保持在同一页面中.

编辑

在您发表评论之后,您需要禁用捕获提交事件并阻止其传播的NgForm指令的行为.见这一行:https://github.com/angular/angular/blob/master/modules/%40angular/forms/src/directives/ng_form.ts#L141.

为此,只需将ngNoForm属性添加到表单:

<form ngNoForm action="https://www.google.com" target="_blank" method="POST">
  <input name="q" value="test">
  <button type="submit">Search</button>
</form>

在这种情况下,将为您的表单提交打开一个新窗口.

希望它能帮到你,蒂埃里

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读