Angular 如何将数组中的对象指定给变量?
我试图从数组中分配一个对象,该数组将始终有一个对象,因为我在调用函数时已将其过滤掉 我有我的Angular 如何将数组中的对象指定给变量?,angular,typescript,angular-components,Angular,Typescript,Angular Components,我试图从数组中分配一个对象,该数组将始终有一个对象,因为我在调用函数时已将其过滤掉 我有我的currentAccount:UserAccount[]数组,我确信只有一个类型为UserAccount的对象。我试图将单个对象分配给变量对象account:UserAccount本身,而不是将其保留为数组。这是我的帐户.component.ts: currentUser: User; currentAccount: UserAccount[]; account: UserAccount; constr
currentAccount:UserAccount[]代码>数组,我确信只有一个类型为UserAccount
的对象。我试图将单个对象分配给变量对象account:UserAccount代码>本身,而不是将其保留为数组。这是我的帐户.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()
,尝试从数组中提取该对象,并将其映射到我的帐户。我只是好像没能得到它
但是需要注意的是,每当我使用任何数组方法尝试获取对象时,我的控制台在加载页面时都会抛出一个错误:
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
中的属性,原因是此.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');
}
);