0

I am creating a provider to make the connection between my server and my component, I have a form and I want to send it to my server.

When I click on submitting the form, I call the onsubmit

 onSubmit() {
    let valueSubmit = Object.assign({}, this.formulario.value);
    let result = this.categoriaSevice.insert(JSON.stringify(valueSubmit));
    console.log(result);
  }

my service categorySevice insert method performs this execution

insert(form) {
    this.http
      .post(
        'http://localhost:80/api/index/category/',
        form,
        { headers: { 'token': 'asd.asd==.asd=', 'header2': 'value2' } }
      )
      .subscribe(
        dados => {
          return this.afterAccess(dados);
        },
        (error: any) => alert('erro')
      );
  }

  afterAccess(dados) {
    console.log(dados.result);
    if (dados.result) { 
      if (dados.result == true)
        return true; 
      else
        return dados.result; 
    }
  }

}

note that in the afterAcess class it returns me the result it got from the server, now I wanted to retrieve this value and be able to display it in the onsubmit of my component.

how can I make this call let result = this.categoriaSevice.insert (JSON.stringify (valueSubmit)); wait for the result to load the result variable and display it in the console.log

Emiry Mirella
  • 567
  • 1
  • 7
  • 21
  • Your insert method doesn't return anything. You need to learn about asynchronism and observables. – JB Nizet Jul 22 '18 at 14:11
  • @EmiryMirella, first: NOT use the old and depreecated http, use httpClient -so you can forget stringify, see https://angular.io/guide/http#httpclient, second: in general remember: "a service return observables, a component subscribe to the services". That's not subscribe in the service. When you want a service make "something" and return another thing use switchMap (this.httpClient.post(..).pipe(switchMap(res=>return afterAcces(res))) – Eliseo Jul 22 '18 at 17:56
  • Hello, hello eliseo thanks for the feedback, the fact that I use this switchMap I will retrieve the return in the class that called the method? – Emiry Mirella Jul 22 '18 at 20:49

0 Answers0