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