如何使用Angular 6将对象发布到JSON中的数组

时间:2018-09-20 18:33:37

标签: json angular

因此,我正在对Angular 6功能进行有趣的测试,以学习它并运行json-server将db.json加载到localhost服务器以通过服务调用获取,您可以在此处查看

{
 "customers": {
 "testingTitle": "Testing Title",
 "trainData":[
 {
  "id": 1,
  "name": "Test Name 1",
  "email": "customer001@email.com",
  "tel": "0526252525"
 },
 {
  "id": 2,
  "name": "Test Name 2",
  "email": "customer002@email.com",
  "tel": "0527252525"
 },
 {
  "id": 3,
  "name": "Customer003",
  "email": "customer003@email.com",
  "tel": "0528252525"
 },
 {
  "id": 4,
  "name": "123",
  "email": "123",
  "tel": "123"
 }
 ]
}

我有一个test.service.ts如下所示:

import { Injectable } from '@angular/core';
import {HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders, HttpParams} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { catchError, map } from 'rxjs/operators';
import 'rxjs/add/observable/throw';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

class Test {
  testingTitle: string;
  trainData:[
    {
      id : number;
      name: string;
      email: string;
      tel: string;
    }
    ];

}

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

  constructor(private http: HttpClient) {}

  public getAllTests(): Observable<Test[]>{
    const params = new HttpParams().set('_page', "*").set('_limit', "*");
    return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
  }

  public postTests(object) {
    return this.http.post("http://localhost:3000/customers", object).subscribe(data => {console.log("POST Request is successful ", data);},error => {console.log("Error", error);});
  }
}

我有我的test.ts来控制我的通话等。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {TestService} from "./test.service";


class Customer {
  id : number;
  name: string;
  email: string;
  tel: string;
}

@Component({
  selector: 'sample-template',
  templateUrl: './test.component.html'})
export class TestComponent implements OnInit {
  testForm: FormGroup;
  testForm2: FormGroup;
  public test: any;
  name: string = '';
  email: string = '';
  tel: string = '';
  public id: any;

  constructor(private httpClient:HttpClient, private fb: FormBuilder, private TestService: TestService) {}




  loadTasks(): void{
    this.TestService.getAllTests().subscribe(response => {this.test = response;
    console.log(this.test)})

  }

  ngOnInit() {

    let trainData = [];

    this.loadTasks();

    this.testForm = this.fb.group({
      testCd: 'Select'
    });

    this.testForm2 = this.fb.group({
      id: this.id,
      name: this.name,
      email: this.email,
      tel: this.tel
    })
  }

  changeDropdown(formControl: FormControl, option: string): void {
    formControl.patchValue(option);
    console.log(option);
  }

  submitForm(){
    let last:any = this.test[this.test.length-1];
    this.id = last.id+1;
    console.log(this.id);
    this.testForm2.value.id = this.id;
    console.log(this.testForm2.value);
    this.TestService.postTests(this.testForm2.value);
  }
}

我的html页面包括以下内容:

<label class="modelo-label">{{test?.testingTitle}}</label>
<form [formGroup]="testForm">
<div class="dropdown modelo-dropdown">
  <label for="testCd" class="modelo-label">Testing</label>
  <button class="btn btn-default dropdown-toggle" data-toggle="dropdown" role="button" id="testCd" aria-haspopup="true" aria-expanded="true">{{testForm.get('testCd').value}}</button>
  <div class="dropdown-menu modelo-dropdown-menu" aria-labelledby="testCd">
    <a class="dropdown-item" *ngFor="let tests of test?.trainData; let i = index" id="tests.name" (click)="changeDropdown(testForm.get('testCd'), tests.name)">{{tests.name}}</a>
  </div>
</div>

  <form [formGroup]="testForm2" (ngSubmit)="submitForm()">
  <div class="row">
    <div class="col-12 col-sm-4 group">
      <input type="text" id="name" formControlName="name" class="modelo-text-input"
             [ngClass]="{'ng-not-empty' : testForm2.get('name').value.length !== 0}">
      <label for="name">Name</label>
    </div>
  </div>
  <div class="row">
    <div class="col-12 col-sm-4 group">
      <input type="text" id="email" formControlName="email" class="modelo-text-input"
             [ngClass]="{'ng-not-empty' : testForm2.get('email').value.length !== 0}">
      <label for="email">Email</label>
    </div>
  </div>
  <div class="row">
    <div class="col-12 col-sm-4 group">
      <input type="text" id="tel" formControlName="tel" class="modelo-text-input"
             [ngClass]="{'ng-not-empty' : testForm2.get('tel').value.length !== 0}">
      <label for="tel">Telephone #</label>
    </div>
  </div>
  <div class="col-1 group generateButton">
    <button class="btn btn-primary" type="submit">Submit Info</button>
  </div>
  </form>

我的问题是,我已经为发布设置了所有内容,而我想做的就是将testForm2.value发布到JSON,但在JSON中的“ trainData”:[{}]下。如果我将所有其他对象放到json内,而仅在“客户”之后放置数组,那么我就能做到:...我到底缺少什么?我现在实际上使我感到困惑,并且我可能会对此过度考虑。如果我仅在“客户”之后放置数组,那么我目前在此代码中的帖子就可以工作:....所以代替我传递作为testForm2.value对象的对象,我还需要做什么?我希望这是有道理的。

1 个答案:

答案 0 :(得分:1)

您的代码中有些奇怪的事情。第一:

在您的API中

return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));

我想您想在这里做的是:(管道是无用的,您不用它,它不是数组)

return this.http.get<Test>("http://localhost:3000/customers",{params});

您要在组件中推送更新trainData列表

submitForm(){
    const lastTrainData = this.test.trainData[this.test.trainData.length-1];

    const newTrainData = this.testForm2.value;
    newTrainData.id = lastTrainData.id + 1;

    this.test.trainData.push(newTrainData);

    this.TestService.postTests(this.test);
  }