【发布时间】:2020-06-05 07:11:51
【问题描述】:
我有一份来自 API 的产品列表。此列表在组件中显示和分页。分页更改不会触发 URL 更改或重新加载组件,但它会加载一组新产品。
我需要在组件中获取列表,因为我必须提取/修改它的一些值。所以仅仅在模板中使用AsyncPipe是不够的。
我想出的解决方案是使用BehaviorSubject。我想知道这种方法是否正确。
这是服务:
export class ProductService {
public list$ = new BehaviorSubject<Product[]>(null);
getAll(criteria: any): Subscription {
const path = '/api';
return this.http.post<any>(path, criteria).pipe(
map((response: any) => {
// some mapping …
return response;
})
).subscribe(response => this.list$.next(response));
}
}
这是组件:
export class ProductComponent implements OnInit, OnDestroy {
products: Product[];
page: number = 1;
constructor(
productService: ProductService
) { }
ngOnInit() {
this.productService.list$.subscribe(products => {
this.products = products;
});
this.loadProducts();
}
ngOnDestroy() {
this.productService.list$.unsubscribe();
}
loadProducts() {
this.productService.getAll({page: this.page});
}
onPageChange(page: number) {
this.page = page;
this.loadProducts();
}
}
我的问题是:
- 有更好的方法吗?
- 这是正确的方法吗?
- 所有订阅和取消订阅都正确吗?
- 如果我要在控制器中加载两个具有不同标准的列表,这会失败吗?如果是,我该如何解决这个问题?
【问题讨论】:
标签: angular typescript rxjs observable angular9