TypeError: Converting circular structure to JSON when trying to POST request

In Addition to already provided answers, here is what you can do when you intend to post the entire form values.

Form example:

<form #formData="ngForm" (ngSubmit)="submit(formData)">
    <input ngModel="my value" name="email" id="email" ...>
    ...
</form>

In ts:

submit(formData: any) {
    const data = JSON.stringify(formData.value);
    this.myService.postData(data)...
}

You are getting the values of the entire form from formData.value then stringify using JSON.stringify(obj)

I hope this will help someone.


That's probably because of circular dependency in the object. In that case, it's not possible to stringify but it's always possible to log to browser console. So we can create a very basic pipe for this purpose.

in app.module.ts:

import { LogPipe } from './log.pipe';

@NgModule({
  declarations: [
    //...
    LogPipe,
  ],
})
export class AppModule {}

log.pipe.ts:

@Pipe({name: 'log'})
export class LogPipe implements PipeTransform {
    public transform(value: object): void {
        console.log(value);
        return;
    }
}

Then we can use the pipe for fast logging

{{'some text' | log}}

use form.value as the following code:

      onSubmit(form: NgForm) {
        this.userService.login(form.value).subscribe(
          (res: any) => {
            localStorage.setItem('token', res.token);
            this.router.navigateByUrl('/home');
          },
          error => {
            if (error.status == 400)
              this.tostarService.error('Invalid Username or password!', 'Authentication Failed');
            else
              console.log(error);

          }
        );
      }

The error seems to be due to the fact that i was trying to stringify the entire myForm object where as what i wanted was to stringify only the values

the correct syntax

let Form = JSON.stringify(this.myForm.value);

Tags:

Angular