如何将数组中的对象分配给变量?

How to assign an object from an array to a variable?

我正在尝试从一个数组中分配一个对象,该数组将始终有 1 个对象,因为我在调用该函数时已将其过滤掉。

我有我的 currentAccount: UserAccount[]; 数组,我确定只有一个 UserAccount 类型的对象。我正在尝试将该单个对象分配给变量对象 account: UserAccount; 本身,而不是将其保留为数组。这是我的 account.component.ts:

currentUser: User;
currentAccount: UserAccount[];
account: UserAccount;

constructor(
  private alertService: AlertService,
  private userService: UserService,
  private authenticationService: AuthenticationService,
) {
  this.authenticationService.currentUser.subscribe(
    x => (this.currentUser = x)
  );
}

ngOnInit(): void {
    this.getCurrentAccount();
    this.currentAccount.map(obj => {
      this.account = obj;
    });
  }

getCurrentAccount() {
    this.userService.getAllUserAccounts().subscribe(
      (data: UserAccount[]) => {
        console.log(data);
        this.currentAccount = data.filter(
          x => x.accountName === this.currentUser.firstName
        );
      },
      error => {
        this.alertService.error('Could not retrieve user account ID');
      }
    );
  }

我已经在我的 ngOnInit() 中尝试了 .map().forEach() 来尝试从数组中提取该对象并将其映射到我的 account。我就是不明白。

但是要注意一件事,每当我使用任何数组方法尝试获取对象时,我的控制台都会在页面加载时抛出错误:

ERROR TypeError: Cannot read property 'map' of undefined
    at ViewAccountPayableComponent.ngOnInit (view-account-payable.component.ts:35)
    at checkAndUpdateDirectiveInline (core.js:31909)
    at checkAndUpdateNodeInline (core.js:44366)
    at checkAndUpdateNode (core.js:44305)
    at debugCheckAndUpdateNode (core.js:45327)
    at debugCheckDirectivesFn (core.js:45270)
    at Object.eval [as updateDirectives] (ViewAccountPayableComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:45258)
    at checkAndUpdateView (core.js:44270)
    at callViewAction (core.js:44636)

我想把它提取出来,因为我想使用UserAccount中的属性。

原因是 this.currentAccount 为空,正在异步检索数据,而您正尝试在检索数据之前使用 .map

将逻辑内部的赋值部分移动如下,

getCurrentAccount() {
    this.userService.getAllUserAccounts().subscribe(
      (data: UserAccount[]) => {
        console.log(data);
        this.currentAccount = data.filter(
          x => x.accountName === this.currentUser.firstName
        );
        this.currentAccount.map(obj => {
         this.account = obj;
        });
      },
      error => {
        this.alertService.error('Could not retrieve user account ID');
      }
    );
  }

这应该可以为您完成工作:

this.userService.getAllUserAccounts().subscribe(
  (data: UserAccount[]) => {
    console.log(data);
    if (data) {
      this.account = data.find(x => x.accountName === this.currentUser.firstName);
    };
  },
  error => {
    this.alertService.error('Could not retrieve user account ID');
  }
);