-1

Can't understand the http module from angular, all works good, but when i insert new data and do the new request, it is in different order, the request get is executed before the POST

The init event (it works)

ngOnInit() {
    this.refresh();
 }
  refresh(){
    this.ps.getFamProv().subscribe((data: any) => {this.famProv = data.familias;});

  }

The server log:

POST /api/provf/ 201 12.381 ms - 135
GET ALL

Then insert new item

 onSubmit() {
    //POST 
        var res=this.ps.addFamProv(this.formAddP.value.name,
                 this.formAddP.value.rfc);
        this.modalService.dismissAll();
//CALLING THE REFRESH METHOD
        this.refresh();
//TRY THIS 
/*res.then( ()=>{
      this.refresh();
      console.log("refresh");

    });*/
      }

Server log (first get the data and then create the new item)

GET /api/provf 304 14.565 ms - -
CREATED PROV FAM

And the Service:

 addFamProv(name, rfc) {
    const obj = {
      name: name,
      rfc: rfc
    };
    return this.http.post(`${this.uri}/provf/`, obj).subscribe(res => {return res;} );
  }

  getFamProv() {return this.http.get(`${this.uri}/provf`);}

Use Await or Async ??

grijalvaromero
  • 589
  • 1
  • 6
  • 20
  • Your server log looks a little odd, since your code says you're doing a post, but your log shows a GET. It also shows a GET against `/api/prov`, but your code only show `/provf`. The log also seems to show a 304 return status code, which is Not Modified... – Heretic Monkey Sep 19 '19 at 20:08
  • oh is beacause i delete the request for /api/prov route only for this example – grijalvaromero Sep 19 '19 at 20:12
  • Seems to me like you want to do your GET after your POST. I'd do something like `res.then(() => this.refresh());` to make sure. But it's not clear what you mean by "it is in different order". – Heretic Monkey Sep 19 '19 at 20:15
  • i try res.then( ()=>{this.refresh(); but it's not works the server firs recieves the GET request and then the POST request – grijalvaromero Sep 19 '19 at 20:37
  • Sorry, I didn't notice that you had a subscribe on your post for some reason. I'd remove that, just return `this.http.post(...)` and then do `res.subscribe(() => this.refresh())`. – Heretic Monkey Sep 19 '19 at 20:39
  • it works thank you very much, I supose the subscribe method do asynchronous the function I will have to read a little more – grijalvaromero Sep 19 '19 at 20:46

1 Answers1

1

I only remove the suscribe function

onSubmit() {
    var res=this.ps.addFamProv(this.formAddP.value.name,this.formAddP.value.rfc);
    res.subscribe( (res) => {
      this.refresh();
    });
    this.modalService.dismissAll();

  }

And then

addFamProv(name, rfc) {
    const obj = {
      name: name,
      rfc: rfc
    };
    return  this.http.post(`${this.uri}/provf/`, obj);
  }
grijalvaromero
  • 589
  • 1
  • 6
  • 20