首页 > 解决方案 > 使用 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);
    }




}

标签: angularspring

解决方案


在随附的屏幕截图中,可以清楚地看到响应不是单一的,object而是一个arrayUser 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);
      }
    )
  }

推荐阅读