使用 angular 从后端检索所有数据
Retrieve all data from backend with 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);
});
}
这是问题所在:
我在我的数据库中有一个文档列表,我用我的服务器检索这些文档。 我的 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);
});
}