使用服务从多个组件订阅相同的数据

use a service to subscribe to the same data from multiple compontents

我的 angular5 应用程序中有几个组件需要从 /api/products 请求返回的产品。现在我正在为每个需要产品的组件联系 api。如何在我的服务中获取产品,然后跨多个组件订阅相同的数据?

在我的组件中

    export class MiniSearchComponent implements OnInit {

        products: any;

        constructor(
            private bcProductService: BcProductService
        ) { this.onGetProducts(); }

        onGetProducts() {
            this.bcProductService.getProducts().subscribe(products => {
                this.products = products.data;
            });
        }

    }

在我的服务中

    getProducts() {
        return this.http.get<any>("/api/products");
    }

我的尝试

组件

    onGetProducts() {
        this.products = this.bcProductService.subscribeProducts();
    }

服务

    products:any;

    constructor(private http: HttpClient) {
        this.products = this.getProducts().subscribe(products => {
            console.log('products from service:', products);
            return products.data;
        });
    }

    getProducts() {
        return this.http.get<any>("http://localhost:3200/api/products");
    }

    subscribeProducts() {
        return this.products;
    }

服务

products:any;

constructor(private http: HttpClient) {
    this.getProducts().subscribe(products => {
        console.log('products from service:', products);
        this.products = products.data;
    });
}

getProducts() {
    return this.http.get<any>("http://localhost:3200/api/products");
}

// Make getter of products
get Products() {
    return this.products;
}

分量

HTML

<div *ngFor="let product of Products">
    // template here
</div>

TS

get Products() {
    return this.bcProductService.Products;
}