[英]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. 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用户.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 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寄存器.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寄存器.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).问题是 angular forms 正在设置单个角色,而您的后端需要
roles
(复数)。 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;
}
);
}
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);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.