如何在兄弟组件之间进行通信

时间:2017-07-27 10:21:52

标签: angular angular2-components

我是棱角分明的新手,如果我做错了或采取了错误的方法,请告诉我。

我有一个foodDetails组件,点击buynow按钮,食物被推入阵列。

ShopDataServicefoodDetails组件和headerComponent之间使用的常用服务,在标头组件中,我希望每次用户点击{{中的buynow按钮时 - 都显示产品数组的长度1}}组件。因此,在foodDetails组件中单击buynow时,如何通知标头组件。

foodDetails

FoodDetails组件:

export class ShopDataService {
    products: any[];
    constructor() {
        this.products = [];
    }
    add(product: any) {
        this.products.push(product);
    }
    get() {
        return this.products;
    }
}

这是我的html容器的结构:

buynow(product){
    this.ShopDataService.add(product);
}

标题组件是prac-header,而routerDetail组件在router-outlet

1 个答案:

答案 0 :(得分:1)

在兄弟组件之间进行通信的最佳方式(在我看来)可以通过使用服务来完成:

<强>服务

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();
    }
}
相关问题