【发布时间】:2021-02-22 08:41:49
【问题描述】:
在我的 Angular 应用程序中,我的方法中有以下代码:
let cardArray: string[] = [];
this.cardService.getCards().subscribe((cards) => {
console.log("1", cards);
for (const card of cards.cards) {
cardArray.push(card.id);
}
console.log("2", cardArray);
});
console.log("3", cardArray);
问题是,3 在 1 和 2 之前记录,所以在 observable 之外的数组是空的,在里面是填充的。我怎样才能获得可观察之外的数据?我需要在函数结束时使用它。
您好!
编辑:添加代码
let cardArray: string[] = [];
this.cardService.getCards().subscribe((cards) => {
cardArray = cards.cards;
});
return this.http.post<Object>(
url,
{
cards: cardArray // <-- here the array is empty
},
{
headers: headers
}
);
【问题讨论】:
-
这是异步操作的问题。如果你想使用
cardArray数据执行一些代码,你应该在传递给订阅方法的函数内部执行。 -
您正在使用 Observable 它是异步的,请提供您愿意做什么来代替 console.log("3"....)?
-
嗨,我用更多代码更新了我的问题。
-
作为 Liam 的回答,您应该在订阅中调用您的 Api。
标签: angular typescript rxjs observable