Tadej Vozlic
Tadej Vozlic

Reputation: 447

Redirect after post in angular

Hi I am writting a post request from my site to external site. After successfull post, it should automatically redirect to the given url with parameters given as 2nd parameter showed in form of that site, but it just won't happen. I tried putting responseType: "text" as 3rd parameter, which resulted a html of page in response that i want to redirect to. How can I perform an actual redirect without text response?

My function looks like that:

sendRequest() {
    //url that I am posting to and it should redirect to, params are given HTTPParams
    this.http.post(this.url,this.params)
      .subscribe(
        data => {
         //apparently following line is not needed.
         this.router.navigateByUrl(this.url);
        },
        error => {
          console.log("Error", error, this.params);
          this.data = error;
            },
        () => {
          console.log("POST is completed");
        });

  }

Upvotes: 3

Views: 12218

Answers (2)

Tadej Vozlic
Tadej Vozlic

Reputation: 447

I found a solution. As fjc commented, i just had to use action="post" in html with url. Previously i tried that, but nothing happened. After hours of debugging i found out that Formsmodule is overriding/preventing submitting the form, so that way didn't work.

Upvotes: 1

Alexandre Bazile
Alexandre Bazile

Reputation: 61

You should not be using "router.navigate" in this case as using it would mean that you want to navigate to a route defined internally in your app.

Please try this instead :

sendRequest() {
    //url that I am posting to and it should redirect to, params are given HTTPParams
    this.http.post(this.url,this.params)
      .subscribe(
        data => {
         //apparently following line is not needed.
         //this.router.navigateByUrl(this.url);
         window.location.href = this.url;
        },
        error => {
          console.log("Error", error, this.params);
          this.data = error;
            },
        () => {
          console.log("POST is completed");
        });

  }

It should redirect to the said url, leaving the angular app

Upvotes: 0

Related Questions