兄弟组件之间如何通信

How to communicate between sibling components

我是 angular 的新手,如果我做错了什么或采取了错误的方法,请告诉我。

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

ShopDataServicefoodDetails组件和headerComponent之间的常用服务,在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,而router-outlet

中的foodDetail组件

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

服务

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();
    }
}