如何将数组的可观察对象转换为数组或遍历数组的可观察对象以获取值?

How do you convert observable of array to array or iterate through observable of array to get a value?

所以我想从返回的可观察对象中获取 id 以将其用于另一个服务调用。

export class CustomerComponent{
  current: Customer;
  orders: Observable<Order[]>;
  orderitems: Observable<OrderItem[]>;
  o: Order[]= [];
  orderid: number;
    
  constructor(
    private router:Router,
    private vs: AccountverificationService,
    private os:OrderService, 
    private ois:OrderItemService) 
  {
    this.vs.current.subscribe(x=>this.current=x);
  }

  ngOnInit() {
    this.orders = this.os.getOrders(this.current.id).pipe(
      map((orderz:Order[]) => this.o = orderz)
    );
        
    this.o.forEach((or: Order) => {
      this.orderid = or.id;
    })
    this.orderitems = this.ois.getOrderItems(this.orderid);  
  }
}

我在这里做的是调用获取所有订单服务(通过客户 ID 获取它们)。 然后对于每个订单,我想获取其订单 ID 以调用获取订单项目服务。 我在考虑两个选择:

  1. 直接遍历Observable<Order[]>并提取orderid。
  2. Observable<Order[]>转换为数组Order[]并循环数组得到orderid

但是,在我的代码中,我尝试了第二个选项。

我用了.pipe(map

但它不起作用,orderid 仍未定义。 连订单都未定义!

有什么建议吗? 谢谢。

今天试过了,还是不行!!!帮助:(

this.orders = this.os.getOrders(this.current.id).pipe(
  tap(orderz => {
    orderz.forEach((or :Order)=> {
      this.orderid = or.id;
    });
  })
)

我不确定您要查找的最终输出是什么。但总的来说:

  • 使用 switchMap 映射到 Observable。
  • 使用forkJoin并行执行多个完成的可观察对象。

要从您必须订阅的任何 Observable 中获取值。

orders$: Observable<{ orderId: string, orderItems: any[] }>;

ngOnInit() {
  this orders$ = this.os.getOrders(this.current.id).pipe(
    switchMap((orderz:Order[]) => forkJoin(
      // map every order to an observable that emits your required data for that order
      orderz.map(o => this.ois.getOrderItems(o.id).pipe(
        // e.g. an object containing the order id and the order items for this id
        map(orderItems => ({ orderId: o.id, orderItems }))
      ))
    ))
  )
}
<ng-content *ngIf="orders$ | async as orders">
  <div *ngFor="let order of orders">
    {{ order | json }}
  </div>
</ng-content>