0

I need to pass data from one component to another but I'm having a hard time doing so.

I have an Observable that I need to pass as Subject which is another Observable. How do I do that? The way I currently have is not working as it gets in the target component undefined.

This is what I have:

card.component.ts (where it all begins)

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);
}

If I console.log() the airportPickup I get the object. No issues. The problem is when I get it in the other component, I get it as undefined.

flight-info.component.ts (the target)

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

The service I have this:

airportPickupDropoff = new Subject<any>();

MrRobot
  • 1,001
  • 1
  • 14
  • 34

2 Answers2

2

You will need to subscribe to the observable, or chain it with RxJS operators(such as tap), in order to assign the values from the observable into your airportPickupDropoff Subject.

Option 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);
  });
}

Option 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();
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
0

Maybe would be better to send data via Subject instead of another Observable?

showBox(studentID) {
  ///...
  airportPickup.subscribe(apdata => this.studentService.airportPickupDropoff.next(apdata));
}
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68