我想在用户甚至打开该组件之前加载http
请求的数据。
this.productService.getProducts().subscribe(list => {
console.log('List: ', list);
this.productList = list;
});
原因是此请求需要较长的响应时间,因此会降低应用程序性能。是否有任何方法可以在不了解用户的情况下预先加载此数据,从而使用户在访问组件时不必等待那么长时间。
答案 0 :(得分:0)
您可以在服务加载时执行请求,然后将响应保存在服务上。即:
class ProductService {
let products: Array<Product>;
constructor () {
this.getProducts.subscribe((products: Array<Product>) => {
this.products = products;
});
}
}
然后在您的组件中,仅引用this.productService.products;
如果您希望在加载组件时仍不会返回请求,则可以设置一个主题,该主题在getProducts调用返回时可以解决。然后在您的组件中订阅。
class ProductService {
let products: Array<Product>;
let productsLoaded: Subject<Array<Product>> = new Subject();
constructor () {
this.getProducts.subscribe((products: Array<Product>) => {
this.products = products;
this.productsLoaded.next(this.products);
});
}
}
然后在您的组件中
public ngOnInit () : void {
this.productList = this.productService.products;
if (!this.products) {
this.productService.productsLoaded.subscribe((products: Array<Product>) => {
this.productList = products;
});
}
}