Angular - 将一个可观察对象的值分配给另一个可观察对象的字段

Angular - Assigning value of an observable to a field of another observable

我正在尝试将一个 observable 的值分配给另一个 observable 的字段。 这是我的代码:

products$.pipe(tap( products => {
  this.data$ = this.data$.pipe(map(data => {
    data.products = products;
    console.dir(data.products);
    return data;
  }));
}));

你不能return这样的数据。您需要创建和观察者并将数据传递给它并订阅它以获取 data ,如下所示:

const testFunction = () => {
return new Observable((observer) => {

 products$.pipe(tap( products => {
    this.data$ = this.data$.pipe(map(data => {
    data.products = products;
    console.dir(data.products);
    observer.next(data);
    observer.complete();
   }));
 }));
})
}
.
.
.
.
// subscribe it to get the data

testFunction.subscribe(data => {
    console.log(data)
});

您可以使用 switchMapmap 运算符来实现,以创建具有所需数据和产品的新可观察对象,如下所示:

const result$ = this.data$.pipe(
  switchMap((data) =>
    products$.pipe(
      map((products) => {
        data.products = products;
        console.log(data.products);
        return data;
      })
    )
  )
);

// Now you can subscribe to the new `result$` observable, and get the data with products:
result$.subscribe((data) => console.log(data.products));