作为 Subject 传递和解包 Observable

Passing and unwrapping Observable as Subject

我需要将数据从一个组件传递到另一个组件,但我很难做到。

我有一个 Observable 需要作为 Subject 传递,这是另一个 Observable。我怎么做? 我目前使用的方式在 目标组件 undefined.

中不起作用

这是我的:

card.component.ts (一切开始的地方)

showBox(studentID) {
    const airportPickup = this.studentService.getCurrentStudents().pipe(
        map(snaps => {
            const student = snaps.find( s => s.studentID === studentID );
            return {
                requirePickup: student.pickup,
                whopickup: student.whoPickup
            };
        })
    );
    this.studentService.airportPickupDropoff.next(airportPickup);
}

如果我 console.log() airportPickup 我得到了对象。没有问题。问题是当我在其他组件中获取它时,我将其作为 undefined.

flight-info.component.ts (目标)

getAirportPickup() {
    this.studentService.airportPickupDropoff.subscribe(
        (apdata) => {
            this.airportPickupDropoff = apdata;
        },
        (e) => alert(e)
    );
}

服务我有这个:

airportPickupDropoff = new Subject<any>();

您需要订阅可观察对象,或将其与 RxJS 运算符(例如 tap)链接起来,以便将可观察对象的值分配给您的 airportPickupDropoff 主题。

选项 1:

showBox(studentID) {
  this.studentService.getCurrentStudents().pipe(
    map(snaps => {
      const student = snaps.find( s => s.studentID === studentID );
      return {
        requirePickup: student.pickup,
        whopickup: student.whoPickup
      };
    }),
  ).subscribe(response => {
    this.studentService.airportPickupDropoff.next(response);
  });
}

选项 2:

showBox(studentID) {
  this.studentService.getCurrentStudents().pipe(
    map(snaps => {
      const student = snaps.find( s => s.studentID === studentID );
      return {
        requirePickup: student.pickup,
        whopickup: student.whoPickup
      };
    }),
    tap(response => this.studentService.airportPickupDropoff.next(response)),
  ).subscribe();
}

也许通过 Subject 而不是另一个 Observable 发送数据会更好?

showBox(studentID) {
  ///...
  airportPickup.subscribe(apdata => this.studentService.airportPickupDropoff.next(apdata));
}