[英]Angular: Assign array from JSON object retrieved via API to a variable
[英]How to assign an object from an array to a variable?
我正在嘗試從數組中分配 object,該數組將始終具有 1 object,因為我在調用 function 時已將其過濾掉。
我有我的currentAccount: UserAccount[];
我確信只有一個 object 類型的UserAccount
的數組。 我正在嘗試將單個 object 分配給變量 object 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()
) 來嘗試從數組中提取 object 並將 map 提取到我的account
中。 我只是似乎無法得到它。
但是需要注意的一點是,每當我使用任何數組方法嘗試獲取 object 時,我的控制台都會在頁面加載時拋出錯誤:
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');
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.