【发布时间】:2020-10-31 07:59:25
【问题描述】:
我们有一个与前端无关的 REST-API,这意味着它总是将 IRI 发送到其嵌套资源。因此,要检索一些数据,您总是必须进行多次 http 调用(首先获取父资源,然后是其子资源等) 所以每个国家都有一个链接条目列表。每个条目都链接到一个产品,该产品的类别资源有一个 IRI。
export interface Country {
countryId: number;
name: string;
code: string;
projects: string[]; //contains an array of IRIs for the project resources
entries: string[];
}
export interface Entry {
entryId: number,
country: string,
information: string,
strategy: string,
action: string,
user: string,
product: string,
salesStatus1: string,
salesStatus2: string,
salesStatus3: string,
salesStatus4: string,
salesStatus5: string,
}
export interface Product {
productId: number,
productName: string,
sharepointId: string,
category: string,
plmId: string,
productStatus1: string,
productStatus2: string,
productStatus3: string,
productStatus4: string,
productStatus5: string,
productComponents: string[]
}
export interface Category {
categoryId: number,
name: string,
children: string[]
}
export class Node {
children: Node[] = [];
name: string;
isProduct: boolean;
}
因此,为了使用显示导航树所需的所有数据,我编写了以下代码:
ngOnInit() {
let nodes: Node[] = new Array<Node>();
this.countriesService.getAll()
.subscribe(
(countries) => {
for (let country of countries) {
let countryNode = new Node();
countryNode.name = country.name;
countryNode.isProduct = false;
for (let entryUrl of country.entries) {
this.entriesService.getByUrl(entryUrl).subscribe(
(entry) => {
this.productsService.getByUrl(entry.product).subscribe(
(product) => {
this.categoryService.getByUrl(product.category).subscribe(
(category) => {
let categoryNode = new Node();
categoryNode.name = category.name;
categoryNode.isProduct = true;
countryNode.children.push(categoryNode);
for (let childrenUrl of category.children) {
this.categoryService.getByUrl(childrenUrl).subscribe(
(childCategory) => {
let categoryChildNode = new Node();
categoryChildNode.name = childCategory.name;
categoryChildNode.isProduct = false;
categoryNode.children.push(categoryChildNode);
}
)
}
}
)
}
)
}
)
}
nodes.push(countryNode);
}
this.dataChange.next(nodes);
}
);
}
但是,由于我对 Angular 和 rxjs 有点陌生,我在“等待”直到所有调用完成并且所有数据(因为它的异步)都在那里(因此导航树总是会丢失元素)时遇到问题。像这样链接也是一种丑陋和不好的做法。所以我想重构 rxjs-methods 的代码,但是我完全迷失了如何开始使用它,因为在检索数据后,我必须再次对其进行迭代以获取嵌套资源 IRI,并且还必须为树导航创建 Node 对象。
你能帮我看看如何重构代码吗?
【问题讨论】:
-
我建议在你的情况下使用带有 async/await 语法的 promise,而不是订阅
-
为什么..? Angular 中的一切都是基于 Observables 的。 Async/await 是 Angular 中的一种反模式,应该避免使用。学习 RxJs,值得。
标签: angular typescript rxjs rxjs-observables