I’ve created a user registration page frontend in Angular which seems to have the proper code for POST register method to be called & data to be sent to backend for user registration but no request are being called to the backend, neither are user details be sent, console.log shows nothing for calling register() method & the network tab in browser developer tools is also kinda empty.
Sharing the code for relevant files:
register.component.html
<div class="registrationForm" type="FormGroup">
<form (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="form-group">
<label for="exampleInputUsername">First Name</label>
<input type="text" [(ngModel)]="fname" class="form-control" id="exampleInputUsername" placeholder="eg. John" [ngModelOptions]="{standalone: true}">
</div>
<div class="form-group">
<label for="exampleInputUsername">Last Name</label>
<input type="text" [(ngModel)]="lname" class="form-control" id="exampleInputUsername" placeholder="eg. Doe" [ngModelOptions]="{standalone: true}">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="exampleInputEmail1">Email:</label>
<input type="email" [(ngModel)]="email" name="mail" class="form-control" placeholder="eg. [email protected]" required >
</div>
<!--
<div class="form-group">
<label for="exampleInputEmail1">Email:</label>
<input type="email" name="email" required class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="eg. [email protected]">
</div>
-->
<div class="form-group">
<label>Password:</label>
<input type="password" [(ngModel)]="password" name="password" class="form-control" required>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-left:220px;margin-top:20px;">Submit</button>
register.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from 'src/app/register/userservice'; //import the user service
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; //import form modules
import { catchError, tap } from 'rxjs';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.less']
})
export class RegisterComponent implements OnInit {
registrationForm: FormGroup;
email:string ='';
password:string ='';
fname:string ='';
lname:string ='';
submitted = false;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private UserService: UserService,
)
{
this.registrationForm = this.formBuilder.group({});
}
ngOnInit() {
this.registrationForm = this.formBuilder.group({
email: [this.email, [Validators.required, Validators.email]],
password: [this.password, [Validators.required, Validators.minLength(6)]],
fname: [this.fname],
lname: [this.lname],
});
}
// convenience getter for easy access to form fields
get f() { return this.registrationForm.controls; }
onSubmit() {
console.log('Submit button clicked');
this.submitted = true;
if (this.registrationForm.invalid) {
return;
}
this.UserService.register(
this.registrationForm.controls['email'].value,
this.registrationForm.controls['password'].value,
this.registrationForm.controls['fname'].value,
this.registrationForm.controls['lname'].value)
.pipe(
tap((response: any) => console.log('Response from server:', response)),
catchError((error: any) => {
console.log('Error from server:', error);
return throwError(error);
})
)
.subscribe();
}
}
function throwError(error: any): any {
throw new Error('Function not implemented.');
}
userservice.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private baseUrl = 'http://localhost:8080/'; // replace with your backend URL //backend url for post mapping of user details
constructor(private http: HttpClient) { }
//check the use of 'Observable'
register(email: string, password: string, fname: string,lname: string): Observable<any> {
const data = {
email: email,
password: password,
fname: fname,
lname: lname
};
console.log('User service register method called with user:', data);
return this.http.post(`${this.baseUrl}/api/register`, data);
}
}
My browser console registers submit button being clicked but not about any of the methods, kindly help.
2
Answers
Your
registrationForm.invalid
is always returningtrue
, because you’ve set some validators on you form, but you bind you template elements to local variables (this.email and so on), not FormControl’s.You initialize you form with that variables, but they are used as default values only. Changing them through template doesn’t update the form.
One solution is to bind your template elements to FormControl, not local variables. I recommend you to use
formGroup
andformControlName
directivesYou defined register function inside user.service with observable output. But you are not returning any observable inside the function