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

时间:2019-10-06 16:01:52

标签: angular typescript angular-components

我正在尝试从数组中分配一个对象,该数组将始终具有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');
      }
    );
  }

我在.map()中尝试过.forEach()ngOnInit()尝试从数组中提取该对象并将其映射到我的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中的属性。

2 个答案:

答案 0 :(得分:1)

原因是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');
      }
    );
  }

答案 1 :(得分:0)

这应该为您完成工作:

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');
  }
);