2

I have angular 2 form and I want to save it in the data base using symfony API web service, I'm trying to fetch data from angular form and sent it as json object to the url endpoint via post http request.

this is the component.html

<div class="ui raised segment">
  <h2 class="ui header">Demo Form: Sku</h2>
  <form #f="ngForm"
        (ngSubmit)="onSubmit(f.value)"
        class="ui form">

    <div class="field">
      <label for="skuInput">SKU</label>
      <input type="text"
             id="skuInput"
             placeholder="SKU"
             name="sku" ngModel>
    </div>
    <div class="field">
      <label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note1" id="select1" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select2" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note2" id="select2" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select3" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note3" id="select3" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

    </div>

    <button type="submit" class="ui button">Submit</button>
  </form>
</div>

the service :

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import { savePostEvaluationapi} from '../../constants/api.endpoints';


@Injectable()
export class EvaluationService {
  http: Http;

  constructor(protected _http: Http) {
    this.http = _http;
  }

  savePostEvaluationService(postEvalform) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const data = JSON.stringify(postEvalform);

    return this.http.post("http://evaluation.dev/app_dev.php/api/savePostEvaluation", data, options).map((res: Response) => res.json());
  }

}

and the component.ts

import {Component, OnInit} from '@angular/core';
import {EvaluationService} from '../../services/evaluation/evaluation.service';

@Component({
  selector: 'app-eval-en-cours',
  templateUrl: './eval-en-cours.component.html',
  styleUrls: ['./eval-en-cours.component.css']
})
export class EvalEnCoursComponent implements OnInit {

  constructor(private evaluationService: EvaluationService) {
  }

  ngOnInit() {
  }

  // savePostEvaluation(data: Object) {
  //   this.evaluationService.savePostEvaluation(data).subscribe((dataResponse) => {
  //     console.log('execute' + dataResponse);
  //   });
  // }
    savePostEvaluation(form: any): void {

      this.evaluationService.savePostEvaluationService(form)
        .subscribe(
          data => data.json(),
          () => console.log('done send form to api')
        );
  }

here is the symfony web service :

/**
     * @Rest\View()
     * @Rest\Post("/savePostEvaluation")
     * @return Response
     * @internal param Request $request
     */

    public function savePostEvaluation(Request $request){
        header("Access-Control-Allow-Origin: *");
        $data = json_decode($request->getContent(), true);
        dump($data);die;
    }

when I try to dump the data value it return null object ! any help please !

2
  • Does form in savePostEvaluation() have any value prior to passing to savePostEvaluationService()? It doesn't look like you are binding ngModel to any object properties. See forms documentation. A two binding would look like [(ngModel)]="someModel.propertyName". Updated the bindings and add more information regarding what you are seeing on submit. Commented Jul 7, 2017 at 15:48
  • hanks for sharing answers Alexander :) but I want to send the form as json object like that : { label : label , value : value } to a webservice to save it in the database ! – Commented Jul 9, 2017 at 21:57

1 Answer 1

1

There are a couple of issues with the code your provided that may be causing the issue:

  1. HTML <option> elements do not seem to have value attributes. Without a value there wouldn't be anything that can be passed to the API in terms of selected value.
  2. ngModel is not currently doing anything as it does not have either the one-way [] or two-binding [()] syntax tying to some component class property.

Try creating a model to representing the form data:

export class Foo {
  constructor(
    public sku: string,
    public note1: string,
    public note2: string,
    public note3: string
  ) {  }
}

Then create an instance of the model in EvalEnCoursComponent with some default/empty values:

import { Foo } from './Foo';

export class EvalEnCoursComponent implements OnInit {
   model = new Foo('', '', '', '');
   // rest of code
}

In your form, update the ngModel to utilize two-way binding to ensure model properties are updating on change/select/etc events for each input/select. Otherwise you'd need extract the form values using something like FormData from the #f form object:

<div class="field">
  <label for="skuInput">SKU</label>
  <input type="text"
         id="skuInput"
         placeholder="SKU"
         name="sku" [(ngModel)]="model.sku">
</div>

Also be sure that your <select> elements' <options> actually have value properties:

  <select class="form-control" name="note2" id="select2" ngModel>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
  </select>

Finally on submit, pass this.model to the service instead of the form instance itself:

savePostEvaluation(): void {
    this.evaluationService.savePostEvaluationService(this.model)
        .subscribe(data => console.log(data));
}

Utilizing a class or interface to represent your form data model will provide you more control over your structure and using two-way data binding will automatically update the values of the model.

Hopefully this helps!

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for sharing answers Alexander :) but I want to send the form as json object like that : { label : label , value : value } to a webservice to save it in the database !
You define the data model in any way you want including names of property keys and format of values. This approach gives you the ability to also modify the object as much as needed prior to sending it the server. You may need to provide additional information regarding your issue.
The sample model provided was just an example of how to approach the issue and make it easier and more structured to use angular forms module. Provide the exact data you want to send to the server.
The fields of the form itself will be retrieved from the database with a web service 'GET'
Can you provide the exact data in the exact structure you want to send to the server? That would help to formulate a solution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.