skip to Main Content

I did a spmple backend in spring with a post that creates a new record in db and I’m trying to call it from frontend.
I’m sure that backend side application works well because I’ve tested it on postman.
frontend side I have an input where I insert url and a button to create a new record.

My function in service file:

addPhoto(url: string) {
        console.log('ciaooo')
        this.http.post("http://localhost:8080/api/photos/create", {
            url: url
        })

My component:

  createPhoto() {
    if (!this.formCreate.valid) {
      alert("compilare tutti i campi obbligatori")
    } else {
      //console.log(this.formCreate.controls['url'].value)
      if (this.formCreate.controls['url'].value != null) {
        console.log('hhh')
        let result = this.tservice.addPhoto(this.formCreate.controls['url'].value)
      }else{
        console.log('prop null')
      }
    }
  }

my html:

<form (ngSubmit)="createPhoto()" [formGroup]="formCreate">
        <input type="text" formControlName='url'>
        <button type="submit">Crea</button>
    </form>

I don’t receive errors in console. But function hasn’t effect

2

Answers


  1. You need to subscribe to the Observable returned by http.post.

    this.http.post("http://localhost:8080/api/photos/create", {url}).subscribe()
    
    Login or Signup to reply.
  2. As already mentioned above, you need to subscribe to the post() method.

    To give some context:
    The post(), get(), delete(), etc functions from the HttpClient are RxJS Observables. An Observable is a stream of data. However, the stream is only "flowing" if there is someone listening to it. You listen to a stream by calling the .subscribe() function of any Observable.

    You could write your addPhoto method like this:

    // Replace unknown with the correct type which is returned from the backend
    addPhoto(url: string): Observable<unknown> {
      return this.http.post("http://localhost:8080/api/photos/create", {
          url: url
      })
    

    And then update your usage in the component:

    createPhoto(): void {
      if (!this.formCreate.valid) {
        alert("compilare tutti i campi obbligatori")
    
        return;
      }
    
      const urlControlValue: string = this.formCreate.controls['url'].value;
      if (!urlControlValue) {
        return;
      }
    
      this.tservice.addPhoto(urlControlValue).subscribe((result: unknown) => console.log('result: ', result))
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search