问题描述
我的目标是将位置数组从 results.component (祖父母)传递到 destination-selector.component (父)通过 bid-filter.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>
bid-filter.ts(父级)
@input() locations;
ngOnInit() {
this.isHome = this.router.url === '/home';
console.log(this.locations);
}
此处的日志未定义
bid-filter.html(父级)
app-destination-selector (selectedDestination)="selectedLocation($event)" [destinations]="locations"
[defaultDestinationId]="selectedValues?.destination"></app-destination-selector>
destination-selector.ts(子级)
@input() destinations;
ngOnInit() {
console.log(this.destinations);
}
也显示未定义
我在这里错过明显的东西吗?我检查了一些不适用于我的问题Angular 2 Component @Input not working
的解决方案感谢您的帮助。
解决方法
通过多个组件传递数据可能会造成混乱,并且更容易获得未定义的数据。更好的方法是使用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);
})
);
bid-filter.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);
}