Search code examples
javascriptangularasynchronouspostget

calling GET request after POST request in Angular


I want to call make a GET request after a POST request using Angular.

Here is the code I have so far, is it the good solution?

   update(){
     this.http.post<any>("/ssservice", "products=" + body, options)
       .suscribe({
         complete: () => {
           this.http.get<Product[]>("/ssservice")
             .suscribe({
               (data: Product[]) => products.push(...data),
               err => console.log(err)})
         }
       });
    }

Any help is greatly aprreciated.


Solution

  • Yes off course this is the good approach as http is asynchronous call so in that case better to call any fucntion/code within the success block of http.

    But try to break your code as much as you can. As in your use case you can call another function and call get request within there like this -

    update(){
         this.http.post<any>("/ssservice", "products=" + body, options)
           .suscribe(
             complete: () => {
               this.anotherGetReuqest();
             });
        }
    
    anotherGetReuqest() {
    this.http.get<Product[]>("/ssservice")
       .subscribe({(data: Product[]) => products.push(...data),
        err => console.log(err)})
    }