angular - 使用 Angular 中的类字段的无限制状态
问题描述
问题是关于在 html 视图或控制台中显示类的字段。我的配置:
export class UserDataService {
constructor(
private http:HttpClient
) { }
executeHelloUserBeanService(){
return this.http.get<User>("http://localhost:8081/physio-node/test/admin");
}
}
从 Spring 传递的对象:
public class UserDTO {
public String username;
public String email;
public UserDTO(User user) {
this.username = user.getUserName();
this.email = user.getUserE_mail();
}
}
Angular 中的用户模型:
export class User {
public username: string;
public email: string;
constructor(username: string, email: string){
this.username = username;
this.email = email;
}
}
export class ProfileComponent implements OnInit {
user: User;
name: string = "true";
constructor(
private service:UserDataService
) { }
ngOnInit(): void {
this.refreshProfile();
}
refreshProfile(){
this.service.executeHelloUserBeanService().subscribe(
response => {
this.user = response;
console.log(this.user);
console.log(this.user.username);
}
)
}
所以,console.log(this.user) 似乎是正确的,因为我可以在控制台中看到完整的对象
但是当我尝试在 html 视图中显示 {{user.username}} 时它不起作用并且控制台在行:console.log(this.user.username) 显示:未定义;
@编辑
public class UserService {
private UserTaskRepository userTaskRepository;
public UserService(UserTaskRepository userTaskRepository) {
this.userTaskRepository = userTaskRepository;
}
public UserDTO getUserbyID(String username){
return userTaskRepository.findByUserName(username)
.stream().
map(UserDTO::new).
collect(Collectors.toList()).get(0);
}
}
解决方案
在随附的屏幕截图中,可以清楚地看到响应不是单一的,object
而是一个array
。User Object
所以要么你必须改变后端的实现,比如 return singleobject
而不是像这样array
改变这个refreshProfile()
方法的实现
refreshProfile(){
this.service.executeHelloUserBeanService().subscribe(
response => {
this.user = response[0]; // just read first element from response
console.log(this.user);
console.log(this.user.username);
}
)
}
推荐阅读
- minio - 替换 4 节点集群中的 minio 节点
- sql - 如何连接 2 个表来分配项目?
- python - Django Rest Framework 获取一个查找字段作为超链接列表
- c++ - C++学生成绩平均计算器数组问题
- php - PHP Symfony 4 导出 CSV
- javascript - 如何在 Nodejs 中使用 twitter api 发布表情符号
- javascript - 如何在 mocker-data-generator 中创建 camelCase fake
- java - Spring JMSListener 上的断路器
- ms-access - Access VB中的调整线
- java - @ManyToMany Annotation Hibernate 的问题 - 外键的列数错误(应该是 3)