javascript - Angular使订阅等待响应

我正在尝试订阅一个 Observable 并从响应中分配一些数据,但不知何故我的代码没有等待响应。基本上 console.log(this.newIds) 首先运行并且始终为空,因为订阅不会等待来自后端的响应。如何强制我的代码等待响应的到来?

 this.repository.getById(Ids).subscribe((response) => {
      console.log(response);
      this.newIds = response.map((id) => {
        return id;
      });
    });
    console.log(this.newIds);

最佳答案

如果您将代码放在订阅回调中。它将在您收到后端的响应后执行。您在此函数之外编写的所有代码都将直接执行。

     this.repository.getById(Ids).subscribe((response) => {
          //Code will execute when back-end will respond
          console.log(response);
          this.newIds = response.map((id) => {
            return id;
          });
          console.log(this.newIds);
        });
//Code will execute immediately

另请参阅:https://angular.io/guide/observables#creating-observables

https://stackoverflow.com/questions/71420974/

相关文章:

rust - 如何在 CLI 应用程序中处理 "./"、 "~/"和相关参数

apache-kafka - 如何获取 Kafka Debezium MySQL 连接器的 data

Flutter - 是否应该将 firebase_options.dart 添加到 gitignor

javascript - 如何根据属性值从单个对象数组创建多个对象数组

linux - "No Such Process"消耗GPU显存

c - 幂函数给出的答案与 C 中的 math.pow 函数不同

c - 使用宏从一组给定的不同值中查找不等于任何值的值

r - 识别匹配对并创建一个公共(public) key

spring-boot - 用 vaadin hilla 代替 flow 有什么好处

javascript - 数组方法练习