0

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

我有一个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>();

4

2 回答 2

2

您将需要订阅 observable,或将其与 RxJS 运算符(例如tap)链接起来,以便将 observable 中的值分配给您的airportPickupDropoff Subject。

选项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();
}
于 2019-11-20T14:34:04.360 回答
0

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

showBox(studentID) {
  ///...
  airportPickup.subscribe(apdata => this.studentService.airportPickupDropoff.next(apdata));
}
于 2019-11-20T14:34:58.520 回答