Home > Blockchain >  angular Post API using spring boot not working
angular Post API using spring boot not working

Time:06-27

I have a component in angular, which is a registered component, and I tried to connect it into springboot backend which is save data (I try it in postman and it's working)

what I do that I create form in angular html

<section id="contact-page" >
  <br><br><br>
  <div >
      <div >
          <div >
              <div >
                  <div >
                      <h1>Register</h1>
                  </div>
                  <div >
                      <form id="register-form" [formGroup] = "RegisterForm">
                          <div >
                              <div >
                                  <div >
                                      <input formControlName="firstName" type="text" name="firstName" type="text" placeholder="Your First Name" required="required">
                                  </div>
                              </div>
                              <div >
                                  <div >
                                      <input formControlName="lastName"  type="text" name="lastName" type="text" placeholder="Your last Name" required="required">
                                  </div>
                              </div>
                              <div >
                                  <div >
                                      <input formControlName="serialNumber" type="number" name="serialNumber"  placeholder="Your serial Number"  required="required">
                                  </div>
                              </div>
                              <div >
                                <div >
                                    <input formControlName="email" type="text" name="email"  placeholder="Your email"  required="required">
                                </div>
                              </div>
                                <div >
                                  <div >
                                      <input formControlName="mobileNumber" type="text" name="mobileNumber"  placeholder="Your mobileNumber"  required="required">
                                  </div>
                            </div>
                            <div >
                              <div >
                                  <input formControlName="country" type="text" name="country"  placeholder="Your country"  required="required">
                              </div>
                            </div>
                            <div >
                              <div >
                                  <input formControlName="password" type="password" name="password"  placeholder="Your password"  required="required">
                              </div>
                            </div>

                            <div >
                              <div >
                                  <input  type="password"   placeholder="Confirm password"  required="required">
                              </div>
                            </div>
                            <br><br>
                            <a routerLink="/abcd" routerLinkActive="active"><b>   click here if u have an account</b></a>
                              <div >
                                  <div >
                                      <button  routerLink="/HomePage" routerLinkActive="active"  type="submit" >REGISTER</button>
                                  </div>
                              </div>

                          </div>

                      </form>
                  </div> <!-- main form -->
              </div> <!--  contact from -->
          </div>
      </div>
  </div>
  <br><br><br>

</section>
 

then I complete with ts file which is connect into register endpoint, in order to save data:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  RegisterForm : FormGroup = this._formBuilder.group({
    firstName : ['' , Validators.required],
    lastName : ['' , Validators.required],
    serialNumber : ['' , Validators.required],
    email : ['' , Validators.required],
    mobileNumber : ['' , Validators.required],
    country : ['' , Validators.required],
    password : ['' , Validators.required]

  });
  constructor(private _formBuilder : FormBuilder ,
    private _http : HttpClient) { }

  ngOnInit(): void {

  }
  onSave() : void {
    let firstName = this.RegisterForm.get('firstName')?.value
    let lastName = this.RegisterForm.get('lastName')?.value
    let serialNumber = this.RegisterForm.get('serialNumber')?.value
    let email = this.RegisterForm.get('email')?.value
    let mobileNumber = this.RegisterForm.get('mobileNumber')?.value
    let country = this.RegisterForm.get('country')?.value
    let password = this.RegisterForm.get('password')?.value

    let body = {
      firstName: firstName,
      lastName : lastName ,
      serialNumber : serialNumber,
      email:email,
      mobileNumber:mobileNumber,
      country : country,
      password:password
    }

    this._http.post("http://localhost:8085/employee/save" , body)
    .subscribe(x=> console.log(x))

   }

}

But what I get that no form appears, and error in inspect screen showed This is the error:

enter image description here

This is the first problem, second one that in spring boot app employee model I have Role attribute which is of type enum {SUPER_USER, USER, AUDTIOR}

but I don't know how I can handle it in an angular app, so how can I add it and how can U show them in the UI? I tried to use select but it's not working.

This is enum class in spring :

public enum Type {
    USER ,
    SUPER_USER,
    AUDITOR
}

and this is Employee ( user ) model :

public class Employee implements UserDetails {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    @Column(name = "serial_number")
    private long serialNumber;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "role_id")
    private Role role;
    private String email;
    private String mobileNumber;
    private String country;
    private String password;
    private boolean isDeleted;


}

CodePudding user response:

For your angular side of the application , you should follow the best practice while working with APIs. On a high level , below should be the steps do achieve the same.

  1. First of all, you should have a separate service.ts file ( e.g. 'Registration.service.ts' ) file. You can either create it via Angular CLI by command ng generate service Registration. This service file should interact with backend and not the component typescript file ( as per your question ). Again this is just a best practice and the way you are trying to connect will also work.

  2. Secondly, Import HttpClientModule in app.module.ts file :

    import {HttpClientModule} from '@anuglar/common/http'

  3. In the service typescript file , inject httClient, as below :

    constructor(private httpClient: HttpClient) {}

  4. Thirdly, while invoking api, you should mention proper HttpHeaders. Example as below :

    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=UTF-8', }), };

  5. Next, you should either return an observable from the service typescript file and subscribe it in component ts file or work with the received response in the service.ts file only. NOTE : In various projects, I return an observable from the service typescript file. Example below :

    return this.httpClient.post( ${baseURL}abcFeature/?user=123, httpOptions );

  6. Finally, consume the response in the component typescript file.

Hope this will help. Let me know if this will fix the problem on the angular side of the things.

CodePudding user response:

Try to import HttpClientModule in app.mpdule.ts

If you have role in yur User entity Spring boot

You can for exemple do this in yur .ts

let body = {
      firstName: firstName,
      lastName : lastName ,
      serialNumber : serialNumber,
      email:email,
      mobileNumber:mobileNumber,
      country : country,
      password:password,
      role:"AUDITOR"
    }
  • Related