httpClient on error refreshes the url in Angular

584 views Asked by At

I am trying to use httpClient in Angular to make API calls. Here is my code where I am making the api call.

This is my httpPost method in authService:

this.authService.httpPost("/api/Users/requestNew", payload).subscribe(
  (data) => {
    console.log(data);
    this.inputForm.reset();
  },
  (error) => {
    let errorMessage = "Ooooops. An error occured. Please refresh and try again.";

  }
);

auth.service.ts

constructor(
  private http: HttpClient, 
  private dataService: DataService
) {}

httpPost(url, payload) {
  return this.http.post(
    this.url_base + ":" + this.port + url,
    payload, {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        Authorization: localStorage.getItem("id_token")
      })
    }
  );
}

Now, in the payload I am intentionally missing a field, as a result the server is throwing an error. This is the error I get from the server:

http://192.168.0.15:3000/api/Users/requestNew 450 (unknown)

Response from server:

{"error":{"statusCode":"450","message":"Duration is not set.","code":"MISSING_FIELD"}}

Now the problem I am facing is my page gets refreshed automatically. This was my original url: http://localhost:4200/user/new, after api call the page gets refreshed with this new url http://localhost:4200/user/new?. An extra question mark is getting added and I am not sure why the page is getting refreshed. It should not be refreshed as no where in my logic I have written so.

Edit

I have a formGroup

inputForm: FormGroup;
durationsControl: FormControl = new FormControl(null, [
  Validators.required
]);

ngOnInit(){
    this.inputForm = new FormGroup({
      duration: this.durationsControl,
      //more controls
    });
}

on change of a dropdown I am removing this control:

valueCHanged(e) {
  const type = e.value;
  if (type === "One") {
    this.durationDiv.nativeElement.style.display = "none";
    this.inputForm.removeControl("duration");

  } else {
    this.durationDiv.nativeElement.style.display = "block";
    this.inputForm.addControl("duration", this.durationsControl);
  }
}

If I do not remove the duration control (this.inputForm.removeControl("duration");), then it works perfectly. How is this change resulting in page refresh?

Edit1 I removed the duration control from ngOnInit():

ngOnInit(){
        this.inputForm = new FormGroup({
          // duration: this.durationsControl, ---> removed this
          //more controls
        });
    }

Now it is working fine and the page is not getting refreshed. But I am still not able to figure out the reason.

0

There are 0 answers