我是 Angular 的新手,如果我做错了什么或采用了错误的方法,请告诉我。
我有一个 foodDetails
组件,在点击 buynow
按钮时,食物被插入一个数组。
ShopDataService
是foodDetails
组件和headerComponent
之间使用的公共(public)服务,在header 组件中我想每次都显示产品数组的长度当用户点击 foodDetails
组件中的 buynow 按钮时。那么如何在foodDetails
组件中点击buynow
时通知header组件。
export class ShopDataService {
products: any[];
constructor() {
this.products = [];
}
add(product: any) {
this.products.push(product);
}
get() {
return this.products;
}
}
FoodDetails 组件:
buynow(product){
this.ShopDataService.add(product);
}
这是我的 html 容器的结构:
<div class="container">
<prac-header></prac-header>
<router-outlet></router-outlet>
</div>
header组件是prac-header,而foodDetail组件是router-outlet
最佳答案
(在我看来)兄弟组件之间通信的最佳方式可以通过使用服务来完成:
服务
export class Service {
private valueObs: BehaviorSubject<string> = new BehaviorSubject<string>(null);
public setValue(value: string):void {
this.valueObs.next(value);
}
public getValue():Observable<string> {
return this.valueObs;
}
}
第一个组件
@Component({
selector: 'component-one',
template: `<button (click)="buttonClicked()">clicke me</button>`
})
export class ComponentOne {
constructor(private service: Service){}
public buttonClicked():void {
this.service.setValue("someValue");
}
}
第二个组成部分
@Component({
selector: 'component-two',
template: `{{value | async}}`
})
export class ComponentTwo {
public value: Observable<string>;
constructor(private service: Service){}
ngOnInit() {
this.value = this.service.getValue();
}
}
关于angular - 兄弟组件之间如何通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347976/