How to initialize form using value from an angular service

Asked

Viewed 39 times

1

I’m returning from mine API an integer, and then, with the angular need to show this value as default in this tag:

<input type="text" formControlName="pacienteId" class="form-control">

I know that to initialize forms with values of an object is used [(ngModel)]="objeto.propriedade" but how could I return from my API that entire number using the angular service?

This is my service:

currentId(): any {
  return this.http.get<number>(`${this.baseURL}/currentId`)
}
  • what returns from this url? ${this.baseURL}/currentId?

  • Returns an integer number

  • In the Component where you call this service you can create a function to call it: ex: currentId().then( response => this.pacienteId = response ) Ai call the function you create in the init of the Component

  • I want to show this integer number that returns from this URL every time I initialize the form

  • it would actually be in your form: currentId().then( response => this.seuForm.pacienteId.setValue( response ) )

Show 1 more comment

1 answer

3

Considering the comment you made that your URL returns an integer number and then it would look something like this

service ts.

currentId(){
   return this.http.get(`${this.baseURL}/currentId`)
}

In the Component where you call that service and assemble the form would look something like this:

Component.

import { FormControl, FormGroup } from '@angular/forms';

export class SeuComponent implements OnInit {
  formCad: FormGroup
  constructor(private _seuService: SeuService) { }

   ngOnInit(){
        this.formCad = new FormGroup({
                pacienteId: new FormControl('')
             })

         this.getcurrentId()
    }
    getcurrentId(){
         this._seuService
             .currentId()
             .subscribe( response => {
                    this.formCad.controls.pacienteId.setValue( response)
              })
      }
}

I hope I can help

  • Helped very expensive, thank you very much, just made a simple modification. Instead of 'then()' I put the subscribe method.

  • That’s right.... I forgot rs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.