如何在组件中使用Angular服务将表单数据发布到api

时间:2019-03-07 00:03:46

标签: angular

我在Angular 6中有一个表单,我还编写了一项服务来获取和发布对Web api的请求。我可以很好地处理请求。但是我正在努力将数据从表单发布到api。我拥有的代码无法正常工作。到目前为止,我有:

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class ServicenowService {

  serviceApiUrl: string = 'api/incident';


  constructor(
    private http: HttpClient,

  ) { }

  getAll(): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl)
      .pipe(
        catchError(this.handleError)
      );
  }

  getIncidents(customerId): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

  postIncidents(customerId): Observable<any> {
    return this.http.post<any>(this.serviceApiUrl + "?customer_id=" + customerId, null)
      .pipe(catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something has wrong; Api is not working!'));
  };

}

form.ts

import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Request } from '../../models/request.model'
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AppComponent } from '../../../app.component';
import { ServicenowService } from '../../services/servicenow.service';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse,} from '@angular/common/http';

@Component({
  selector: 'app-service-request',
  templateUrl: './service-request.component.html',
  styleUrls: ['./service-request.component.scss']
})
export class ServiceRequestComponent implements OnInit {

  public customers;
  public customer;

  private customer_id = 7; /// this.appComponent.customer_id;

  serviceForm;

  countries = [
    { name: 'Choose an option' },
    { name: 'United Kingdom', },
    { name: 'United States of America', },
    { name: 'Russia', },
    { name: 'Moscow', },
    { name: 'Africa', },
  ];

  users = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  devices = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  constructor(private service: ServicenowService,
    private appComponent : AppComponent,
    private router: Router,
    private http: HttpClient

  ) {
  }

  ngOnInit() {
    this.serviceForm = new FormGroup({
      u_caller_id: new FormControl(this.users[0], Validators.required),
      u_cmdb_ci: new FormControl('', Validators.required),
      u_destination_country: new FormControl(this.countries[0], Validators.required),
      u_requester_phone_number: new FormControl('', Validators.required),
      u_serial_number: new FormControl(this.devices[0], Validators.required),
      subject: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(5),
        Validators.maxLength(10)
      ])),
      issue: new FormControl('', Validators.required),
    });
  }

  onSubmit() {
    var data = "u_cmdb_ci=" + this.serviceForm.value.u_cmdb_ci;
    this.service.postIncidents(this.customer_id).subscribe((data) => {});
    console.log("data has gone");
       }
  }

我已经将服务注入到组件中,但是它不起作用,我也尝试了以下方法,我知道它只有一个字段,但是我想测试一下但不起作用:

onSubmit() {
    var data = "u_cmdb_ci=" + this.serviceForm.value.u_cmdb_ci;
    this.http.post("api/incident", data).subscribe((res) => {});
    console.log("data has gone");
    }

1 个答案:

答案 0 :(得分:1)

您应该通过发布对象,而不是尝试将其变成URL参数。此外,添加错误处理程序,以便您可以获取一些错误数据来解决所有问题。

onSubmit() {
    var data = this.serviceForm.value.u_cmdb_ci;
    this.http.post("api/incident", data).subscribe(
       (res) => {
          console.log(res);
       },
       (error) => {
          console.log(error);
       }
    );
    console.log("data has gone");
}