0

In Angular 6, I have the following code:

import { Component, OnInit } from '@angular/core'
import { FormGroup, FormBuilder} from '@angular/forms';

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss'],
})

export class FormComponent implements OnInit {
    formulario: FormGroup

    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
        this.formulario = this.formBuilder.group({
            pesquisa: [null],
        })
    }
    teste() {
        console.log(this.formulario.value.pesquisa)
    }
}

How can I export the "this.formulario" so that I can use it in a service?

I am capturing the data entered in an input via ngSubmit and I want to pass it to the url of an API (which is defined in a service).

I am a beginner and I do not find solutions clear enough for my understanding.

callback
  • 3,981
  • 1
  • 31
  • 55
Bruno Sousa
  • 67
  • 2
  • 9
  • 1
    in Angular, components should inject services. So you can call a service passing your form on your submit: `onSubmit() { this.myService.method(this.formulario); }` – Leo Caseiro Jun 06 '18 at 23:56
  • see https://angular.io/guide/dependency-injection-in-action#injectable-and-nested-service-dependencies – Leo Caseiro Jun 06 '18 at 23:57
  • Possible duplicate of [How to submit form to server in Angular2](https://stackoverflow.com/questions/34835516/how-to-submit-form-to-server-in-angular2) – callback Jun 07 '18 at 00:04

1 Answers1

1

You should first inject your service inside your component. So that you can call your service method from the component with your form data as input. This is the recommended way to pass form data to the server. From your service, you can extract all the form data and build a request object. Or else you extract inside component and pass it to service for api calls.

Sample code :

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss'],
    providers : [AppService]
})

export class FormComponent implements OnInit {
    formulario: FormGroup

    constructor(private formBuilder: FormBuilder, private _appService : AppService) {}

    ngOnInit() {
        this.formulario = this.formBuilder.group({
            pesquisa: [null],
        })
    }
    teste() {
       // You can also extract form data inside component itself and then prepare object to pass it to service
       let myData = {
         name : this.formulario.value.userName,
         firstName : this.formulario.value.firstName
       }
        this._appService.saveData(myData);
        console.log(this.formulario.value.pesquisa)
    }
}
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98