另一项服务的订阅数据迟到了

The data for subscribing is coming late for another service

我正在从事一个电子商务项目,我在其中创建了两个服务。授权服务和订单服务。当用户获取日志时,数据存储在用户 class 中,可以通过 AuthService 访问。但是当我为 authservice 订阅用户的数据时,它来晚了(异步),有时用户的 id 无法用于订单服务。

我如何等待订阅直到结果出来? 下面是我的代码示例。任何帮助将不胜感激。

下面是HTML文件代码:

 <div *ngIf="userOrders.length>0">
            <h2>Your Orders</h2>
            <p>Below are the orders and status</p>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Order Id</th>
                        <th>Contact</th>
                        <th>Address</th>
                        <th>Amount</th>
                        <th>Updated At</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{{userOrders.orderId}}</td>
                        <td>Doe</td>
                        <td>john@example.com</td>
                    </tr>

                </tbody>
            </table>
        </div>

下面是ts文件代码:

this._authService.user.subscribe(res=>{
     this.userId=res.id;
      console.log(res)
    })
      console.log(this.userOrders)

      this._orderService.getUserOrders(this.userId).subscribe(res=>{
        this.userOrders=res;
        console.log(res)
      })

  }  

以下是我从前端面临的错误。由于它的响应是异步的,而 HTML 加载长度为 0。

这里有几个解决方案。最简单的如下。在这里,您只能在 authService 具有 return 变量后调用 getUserOrders(...) 函数。

this._authService.user.subscribe(res=>{
 this.userId=res.id;
  this._orderService.getUserOrders(this.userId).subscribe(res=>{
    console.log(res)
  })
})
  console.log(this.userOrders)
}

也许您的问题已解决,但这不是正确的方法,对于这种情况,您可以使用 rxjs 库和管道中的 switchMap

通过这个例子,您将解决两个端点之间的异步问题,第一个可观察对象将发出它的值,“switchMap”将接收该值,并且在这种情况下 return 一个带有用户 ID 的可观察对象.

你终于只有一次订阅了。

详细了解 switchMap

import { switchMap } from 'rxjs/operators'

    this._authService.user
      .pipe(
        switchMap(data => { // this data comes from this._authService.user obseravble
          this.userId = data.id;
          return this._orderService.getUserOrders(data.id); // or this.userId
        })
      )
      .subscribe(response => {
        this.userOrders = response;
      });