I am getting the error in the title and here is the full stack trace, i am not sure what it is, any insight is welcomed!
browser_adapter.js:84 EXCEPTION: Error i
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);
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);
}
);
}
One of the way is you can make use of angular's built-in 'json' pipe also.
For that, you need to add angular pipe in your component the this.myForm needs to pass in the pipe method.
In the template, you can simply use {{ myForm.value | json }}
.
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 {}
@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}}
This code will fail for circular reference:
JSON.stringify(circularReference);
// TypeError: cyclic object value
Use the below code:
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());