从服务获取数据到另一个组件

时间:2019-10-10 08:00:54

标签: angular

组件A 中获得所有用户的列表,当我单击 EDIT 时,我将带有用户ID的数据发送到服务,并从服务发送到组件B  在 service.ts 中,我创建

  selectedUser = new Subject<any>();

来自组件A

this.userService.selectedUser.next(this.user);

组件B

ngOnInit() {
this.userService.selectedUser.subscribe(
  user => {
    this.user = user;
    console.log(this.user);
  },
  data => {
    if (this.user === undefined) {
      this.addNewUserState = true;
      this.createForm();
    } else {
      this.addNewUserState = false;
      this.addNewUserForm.controls["username"].setValue(this.user.username);
      this.addNewUserForm.controls["firstName"].setValue(this.user.firstName);
    }
  }
)
};

在第一个详细信息上,单击我不获取数据,在网络标签中,我获取了所选用户的数据,但是consol.log()未记录任何内容 这是预览 https://ttprivatenew.s3.amazonaws.com/pulse/bozzodj/attachments/11660135/TinyTake10-10-2019-10-00-04.mp4

1 个答案:

答案 0 :(得分:0)

通常在数据异步时发生。
您可以使用 async-await promise

以下操作通过 async-await

完成
ngOnInit() {
  this.userService.selectedUser.subscribe(async user => {
      this.user = await user;
      console.log(this.user);
    },
    data => {
      if (this.user === undefined) {
        this.addNewUserState = true;
        this.createForm();
      } else {
        this.addNewUserState = false;
        this.addNewUserForm.controls["username"].setValue(this.user.username);
        this.addNewUserForm.controls["firstName"].setValue(this.user.firstName);
      }
    }
  )
};