angular - 使用输入绑定将数据从祖父组件传递到子组件
问题描述
我的目标是通过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
任何帮助表示赞赏。
解决方案
通过多个组件传递数据可能会让人感到困惑,并且更容易将数据设为未定义。更好的方法是使用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);
}
推荐阅读
- java - Spring Data JPA:如果 Id 存在,则使用 saveAll 时防止更新
- ios - SwiftUI:在未突出显示的 3 列中启动时预选 NavigationLink
- python - 为什么我的循环没有迭代列表中的第二个相同的值?
- python - 使用 datetime.time 类型重采样 pandas 索引
- php - 将数据插入 laravel 数据库
- python-3.x - 下边界既不是与src大小相同类型的数组,也不是函数中的标量
- c++ - 非图形 C/C++ 代码的 OpenGL 数据类型?
- django - 如何将我的投诉列表呈现到卡片中以便能够查看它们?
- libasound - Aplay 示例格式不可用
- amazon-web-services - 处于连接丢失状态的 Systems Manager 托管实例