在Angular 2中形成具有身体的岗位

时间:2016-07-11 07:30:28

标签: typescript angular

我正在尝试将一个表单发布到带有身体的api我怎么做。到目前为止我已经完成了。我想从表单中获取值并将其发送到api正文。我不知道怎么做到这一点。现在我只是通过身体硬编码但我希望它从表单中获取值并作为正文发送。

 inviteUser() {
        let headers = new Headers();
        headers.append('Content-Type','application/json');
        let body = {
            "UserName": "user1",
            "Email": "user1@atea.com",
            "PartnerId": "1"
        };

        this.http.post('https://localhost:44300/api/apis/InviteUser', JSON.stringify(body), {
            headers: headers
        })
            .subscribe(
            data => this._data = data.json(),
            err => this.logError(err),
            () => console.log(body)
            );
    }

HTML



<h1>Pending Approvals </h1>
<link href="../../Content/bootstrap.css" rel="stylesheet" />
<link href="../../Content/bootstrap-theme.min.css" rel="stylesheet" />
<div class="container">
    <div class="row">
        <div class="col-offset-md-10">
            <button type="button" class="btn-u  pull-center" data-toggle="modal" data-target="#myModal">Invite User</button>
        </div>

    </div>
    <div class="row">
        <div class="col-md-8">
            <div class="table-responsive">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Account Manager</th>
                            <th>Subscription</th>
                            <th>Created By</th>
                            <th>Pending</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let user of _data">
                            <th>{{user.AccountManagerId}}</th>
                            <th>{{user.SubscriptionId}}</th>
                            <th>{{user.CreatedBy}}</th>
                            <th>
                                <button type="button" class="btn btn-xs btn-danger" (click)="approvalPendingRequest(user.SubscriptionId)">
                                    <span class="glyphicon glyphicon-send"></span>&nbsp;
                                </button>
                            
                           </th>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add New User</h4>
            </div>
            <div class="modal-body">
                <form (submit)='inviteUser()'>
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" required
                                name="name">
                    </div>
                    <div class="form-group">
                        <label for="alterEgo">Email</label>
                        <input type="email" class="form-control" required
                                name="alterEgo">
                    </div>
                    <div class="form-group">
                        <label for="power">Partner</label>
                        <select class="form-control" 
                                 name="power">
                            <option *ngFor="let p of powers" [value]="p">{{p}}</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-default" data-dismiss="myModal">Invite</button>
                </form>
            </div>

        </div>

    </div>
</div>
&#13;
&#13;
&#13;

enter image description here

详细

现在我想从表单中获取值并将其作为主体发送给api。

2 个答案:

答案 0 :(得分:1)

你必须使用Form指令和所有这些来从表单获取值并使用http发布它。

你的.html中的

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">

  <div class="col-md-7">
    Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
  </div> 

  <div class="col-md-7">
    Email:   <input type="text" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password'>
  </div>

  <div class="col-md-7">
    partner:   <input type="text" [(ngModel)]='demoInfo.partner' class="form-control" ngControl='partner'>
  </div>

</form>
<br>
<div class='text-center'>
  <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>

并在你的.ts

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'partner': new Control()
        })

比使用http发送数据 -

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
    }

我已经创建了一个相同的例子,你在这里看到等等 Working example

另见 -

答案 1 :(得分:0)

在构造函数中创建表单

  form: ControlGroup;

  constructor(private fb: FormBuilder, private fba: FbaService, private router: Router) {
    this.form = this.createForm();
  }

  createForm() {
    return this.fb.group({
      "name": ["", Validators.required],
      "email": ["", Validators.required],
      "partner": [""]
    });
  }

然后将此表单与html集成。

<form ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
  <div class="form-group">
    <input [ngFormControl]="form.controls['name']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['name'].valid && form.controls['name'].dirty">
      Field Required
    </span>
  </div>
  <div class="form-group">
    <input [ngFormControl]="form.controls['email']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['email'].valid && form.controls['email'].dirty">
      Field Required
    </span>
  </div>
     <div class="form-group">
    <input [ngFormControl]="form.controls['partner']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['partner'].valid && form.controls['partner'].dirty">
      Field Required
    </span>
  </div> 
  <input [disabled]="!form.valid" type="submit" class="btn btn-default" value="Add">
</form>

然后在onSubmit中使用form.value作为主体。

  onSubmit(value) {
    let headers = new Headers();
    headers.append('Content-Type','application/json');

  this.http.post('https://localhost:44300/api/apis/InviteUser',value, {
        headers: headers
    })
        .subscribe(
        data => this._data = data.json(),
        err => this.logError(err),
        () => console.log(body)
        );
  }