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

时间:2018-04-23 16:27:19

标签: angular mean-stack

我的angular5应用中有几个组件需要将请求返回的产品发送到org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0') 。现在我正在联系api,了解每个需要产品的组件。如何在我的服务中获取产品,然后订阅跨多个组件的相同数据?

在我的组件中

/api/products

在我的服务中

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

1 个答案:

答案 0 :(得分:1)

<强>服务

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