简体   繁体   中英

How can I add roles using Angular

I had this problem roles can't added when I'm using angular form whereas JSON test postman register added correctly here in frontend roles always null if someone have an idea how can I solve this issue I'll be glad. Thank you in advance

User.Controller

 @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody RegistrationForm signUpRequest) {
       if (utilisateurRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username is already taken!"));
        }

        if (utilisateurRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Email is already in use!"));
        }

        Set<String> strRoles = signUpRequest.getRoles();

        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);

        } else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);

                        break;


                    default:
                        Role aideRole = roleRepository.findByName(ERole.ROLE_AIDESOIGNANTE )
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(aideRole);
                }
            });
        }
        // Create new user's account
        Utilisateur user = new Utilisateur(signUpRequest.getUsername(),
                signUpRequest.getEmail(),
                passwordEncoder.encode(signUpRequest.getPassword()), signUpRequest.getTelephone(), roles);

        user.setRoles(roles);
        utilisateurRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }

Authentication.Service Angular

 register(user): Observable<any> {
    return this.http.post(AUTH_API + 'signup', {
      username: user.username,
      email: user.email,
      telephone: user.telephone,
      role: user.role,
      password: user.password
    }, httpOptions);

Register.Html

 <div class="form-group">
          <label for="role">Role</label>
          <input
            type="text"
            class="form-control"
            name="role"
            [(ngModel)]="form.role"
            required
            #role="ngModel"
          />

        </div>

Register.ts

 onSubmit() {
    this.authService.register(this.form).subscribe(
      data => {
        console.log(data);
        this.isSuccessful = true;
        this.isSignUpFailed = false;
      },
      err => {
        this.errorMessage = err.error.message;
        this.isSignUpFailed = true;
      }
    );
  }

The problem is that angular forms is setting a single role and your backend is expecting roles (in plural). You can solve it by doing the following:

onSubmit() {
  // use rest operator to get a rest object without role
  const {role, ...rest} = this.form;

  // build userData, containing the role collected above
  // SignUpData is declared on Authentication.service
  const userData: SignUpData = {...rest, roles: [role]};

  // use the userData in your request
  this.authService.register(userData).subscribe(
    data => {
      console.log(data);
      this.isSuccessful = true;
      this.isSignUpFailed = false;
    },
    err => {
      this.errorMessage = err.error.message;
      this.isSignUpFailed = true;
    }
  );
}

Authentication.Service Angular

export interface SignUpData {
  username: string;
  email: string;
  telephone: string;
  roles: string[];
  password: string;
}

@Injectable({providedIn: 'root'})
export class AuthenticationService {

  ...
  register(user: SignUpData): Observable<any> {
    return this.http.post(AUTH_API + 'signup', user, httpOptions);
  }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM