如何在 Angular 中搜索两个而不是两个文档时发出一个服务请求?
How to make one service request while searching for two documents in Angular instead of two?
我正在搜索满足给定条件的文档。在这里,我通过订阅两个不同的请求来搜索存储在两个不同变量中的 surveys
和 exams
。
getEntities() {
this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'survey',
status: 'pending'
})).subscribe((surveys) => {
this.surveys = surveys;
});
this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'exam',
status: 'pending'
})).subscribe((exams) => {
this.exams = exams;
});
}
如何将两个可观察对象保存在一个服务请求中,而不是发出两个单独的请求?
谢谢!
您可以在 rxjs 中为此使用 forkjoin
。
forkjoin: This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all.
getEntites() {
const surveysObservable = this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'survey',
status: 'pending'
}));
const examsObservable = this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'exam',
status: 'pending'
}));
Observable.forkJoin([surveysObservable , examsObservable]).subscribe(results => {
this.surveys = results[0];
this.exams = results[1];
});
}
检查这个工作stackblitz. Learn more about forkjoin here.
我正在搜索满足给定条件的文档。在这里,我通过订阅两个不同的请求来搜索存储在两个不同变量中的 surveys
和 exams
。
getEntities() {
this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'survey',
status: 'pending'
})).subscribe((surveys) => {
this.surveys = surveys;
});
this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'exam',
status: 'pending'
})).subscribe((exams) => {
this.exams = exams;
});
}
如何将两个可观察对象保存在一个服务请求中,而不是发出两个单独的请求?
谢谢!
您可以在 rxjs 中为此使用 forkjoin
。
forkjoin: This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all.
getEntites() {
const surveysObservable = this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'survey',
status: 'pending'
}));
const examsObservable = this.submissionsService.getSubmissions(findDocuments({
'user.name': this.userService.get().name,
type: 'exam',
status: 'pending'
}));
Observable.forkJoin([surveysObservable , examsObservable]).subscribe(results => {
this.surveys = results[0];
this.exams = results[1];
});
}
检查这个工作stackblitz. Learn more about forkjoin here.