首页 > 解决方案 > 使用输入绑定将数据从祖父组件传递到子组件

问题描述

我的目标是通过bid-filter.component (子)将位置数组从results.component(祖父)传递到destination-selector.component(父)。

results.ts(祖父母)

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

此处的日志已定义并显示位置数组

results.html(祖父母)

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

出价过滤器.ts(父)

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

这里的日志是未定义的

出价过滤器.html(父)

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

目的地选择器.ts(子)

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

也显示未定义

我在这里错过了一些非常明显的东西吗?我检查了一些不适用于我的问题的解决方案Angular 2 Component @Input not working

任何帮助表示赞赏。

标签: angularcomponentsinputbinding

解决方案


通过多个组件传递数据可能会让人感到困惑,并且更容易将数据设为未定义。更好的方法是使用Service. 您可以按照以下步骤

创建服务

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

然后将上面的服务注入到更新的locations组件和接收locations **的组件中

results.ts(祖父母)

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

出价过滤器.ts(父)

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


推荐阅读