用angular从后端检索所有数据



问题是:

我有一个列表的文档在我的数据库,我检索与我的服务器。我的angular应用程序需要检索整个文档列表。我的文档列表有一个偏移量。例如:我用偏移量0调用我的服务器并检索从0到600的第一个文档,然后我用偏移量600调用检索从601到1200等…直到我得到一个404的服务器,这意味着结束。

我想在angular中做到这一点,我试着像这样使用'while':

let done = false;
let offset = 0;
const docList = [];
while(!done) {
this.docService.retrieveDoc(url, offset).subscribe(result => {
docList.push(result);
offset = doclist.length;
}, err => {
done = true;
});
}

但这不起作用,同时不要等待服务器响应,只是无限地启动http请求

你们有什么主意吗?:)谢谢你的帮助!

对于循环,您应该执行async/await,因为循环将尽可能快地运行。由于订阅几乎立即完成,因此它将再次调用while,在订阅最终执行之前,这将重复数百次。在循环中使用await将暂停循环,直到动作完成,然后继续。

要保留你所拥有的,你可以这样做:

public async doSomething() {
let done = false;
let offset = 0;
const docList = [];
while(!done) {
try {
const result = await this.docService.retrieveDoc(url, offset).pipe(first()).toPromise();
docList.push(result);
offset = doclist.length;
} catch(e) {
done = true;
}
}
}

如前所述,您还可以采用递归方法完全删除循环。

private docList = [];
public doSomething(url: string) {
this.docService.retrieveDoc(url, docList.length).subscribe(result => {
this.docList.push(result);
doSomething(url);
});
}

最新更新