如何使用 changeDetection onPush with observable



我是Angular2的绝对初学者,

这是我的组件,如何在 HeaderComponent 中更新 this.product 数组,每当在 FoodDetailsComponent 中触发 buynow(( 时

export class HeaderComponent {
products: Array < any > ;
cart: Array < any > ;
Tabs: Array < any > ;
constructor(public ShopDataService: ShopDataService) {
this.products = this.ShopDataService.get();
}
ngOnInit() {}
}

export class FoodDetailsComponent {
@Input()
foodDetail: any;
constructor(private ShopDataService: ShopDataService) {
}
buynow(product) {
this.ShopDataService.add(product);
}
ngOnInit() {}
}

而且我几乎怀疑更改检测是如何工作的,更改检测策略仅适用于子父组件。兄弟组件如何工作?

您需要在获取数据时订阅该服务。

this.ShopDataService.get().subscribe( result => {this.products = result});

另外,请在您的服务中共享代码。

最新更新