Angular 进行订阅以等待响应

any*_*y07 8 javascript asynchronous typescript 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);
Run Code Online (Sandbox Code Playgroud)

小智 6

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

     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
Run Code Online (Sandbox Code Playgroud)

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