【问题标题】:angular empty array outside observable [duplicate]可观察到的角度空数组[重复]
【发布时间】: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


【解决方案1】:

您需要重构代码。它应该更像:

this.cardService.getCards()
.pipe(
   mergeMap((cards) => {
      return this.http.post<Object>(
        url,
       {
          cards: cards
       },
       {
          headers: headers
       }
     );
   })
)
.subscribe();

在这里,我使用RXJS mergeMap 将第一个 observable 的结果通过管道传输到第二个。 注意这仍然是异步的,所以你不能只返回结果。如果你想在更高的地方消费这个,我建议更像:

function postCards(): Observable<Object> {
   return this.cardService.getCards()
    .pipe(
       mergeMap((cards) => {
         return this.http.post<Object>(
            url,
            {
              cards: cards
            },
           {
              headers: headers
           }
        );
     })
   );

}


postCards().subscribe();

你应该阅读更多关于RXJS operators


在这个例子中,有没有办法只使用来自 getCards 方法的 ID 创建一个数组

嗯,是的,也不是。你应该阅读How do I return the response from an asynchronous call?。基本上你的想法是错误的。不要同步思考,你需要开始思考异步。

拥抱 JavaScript 的异步特性!虽然确定 异步操作提供同步对应物(也是如此 “Ajax”),通常不鼓励使用它们,尤其是在 浏览器上下文。

你问为什么不好?

JavaScript 在浏览器的 UI 线程中运行,任何长时间运行的 进程将锁定 UI,使其无响应。此外,还有 是 JavaScript 和浏览器的执行时间上限 会询问用户是否继续执行。

您的问题有various async solutions,正确的取决于您实际想要对这个数组做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 2019-03-24
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多