0

My goal is to pass the locations array from the results.component (grand-parent) to destination-selector.component (parent) through the bid-filter.component (child).

results.ts (grand-parent)

this.subscriptions.add(
      this.customerService.getAllDestinations().subscribe(loc => {
        this.locations = loc.payload;
        console.log("from results",this.locations);
      })
    );

The log here is defined and shows the locations array

results.html (grand-parent)

<app-bid-filter [locations]="locations" [selectedValues]="selectedValues"
          (search)="toggleFilters();search($event)"></app-bid-filter>

bid-filter.ts (parent)

@Input() locations;
    ngOnInit() {
      this.isHome = this.router.url === '/home';
      console.log(this.locations);
     }

the log here is undefined

bid-filter.html(parent)

app-destination-selector (selectedDestination)="selectedLocation($event)" [destinations]="locations"
  [defaultDestinationId]="selectedValues?.destination"></app-destination-selector>

destination-selector.ts (child)

 @Input() destinations;
 ngOnInit() {
    console.log(this.destinations);
  }

shows undefined as well

Am I missing something pretty obvious over here? I checked a couple of solutions which were not applicable to my issue Angular 2 Component @Input not working

any help is appreciated.

  • Use location as Observable i.e `this.locations$ = this.customerService.getAllDestinations().pipe(tap(loc) => loc.payload)` and in template `[locations]="locations$ | async"` – Kamran Khatti Sep 11 '20 at 20:07

1 Answers1

0

Passing data through multiple components may get confusing and more prone to getting data as undefined. A better approach would be to use a Service. You can follow below steps

Create the service

export class MyService() {
  locasionsSubject$ = BehaviourSubject<any[]>([]);
  locasions$ = this.locasionsSubject$.asObservable();
}

The above service is then injected to the component that updates the locations and the component that receives the locations **

results.ts (grand-parent)

constructor(private myService: MyService) {}
this.subscriptions.add(
  this.customerService.getAllDestinations().subscribe(loc => {
     this.locations = loc.payload;
     this.myService.locasionsSubject$.next(this.locations)
     console.log("from results",this.locations);
  })
 );

bid-filter.ts (parent)

constructor(private myService: MyService) {}
ngOnInit() {
  this.myService.locasions$.subscribe({
    next: (locations) => this.locations = locations
  })
  this.isHome = this.router.url === '/home';
  console.log(this.locations);
}

Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74