我正在使用 forkJoin 发出多个服务器请求。这是我在整个应用程序中经常使用的模式,并且效果很好。然而,我们刚刚开始实现在后端完成的用户 Angular 色。我不确定实现 Angular 色的最佳做法是什么,因为我主要是一名前端开发人员,但这是我遇到的问题:
我们的应用程序具有成员和管理员成员 Angular 色。
在每个 View 中,我都必须为成员和管理员成员 Angular 色调用后端,因为 Angular 色不是在前端确定的。
成员数据始终返回给两个 Angular 色,因为成员和管理员成员都有个人数据。
只有当用户是管理员时,才会返回对管理员数据的请求。只要用户没有管理员访问权限,请求就会返回 401 错误。这是我遇到问题的地方。
每当调用返回 401 时,我的订阅方法中的错误方法就会被调用,我无权访问任何已进行的调用,包括与成员数据关联的调用。
在我包含的 forkJoin 代码中,有五个调用传递到方法中。如果用户是管理员,则第三次和第四次调用仅返回数据,而其余调用始终返回成员或管理员。
当用户不是管理员时,第三次调用返回 401,流停止并调用我的订阅方法中的错误处理程序。这显然不是我想要的。我希望流继续,以便我可以在 _data 方法中使用数据。
我只使用 RXJS 6 个月,并且正在学习。也许我应该使用不同的模式,或者也许有办法解决这个问题。对代码示例的任何帮助将不胜感激。在我的代码示例下方,我包含了另一个代码示例,我在其中尝试通过尝试使用 catch 方法来解决问题。它没有用。
我的 View 获取方法:
private getZone() {
this.spinner.show();
this.zonesService.getZone(this.zoneId)
.map(response => {
this.zone = response['group'];
return this.zone;
})
.flatMap(() => {
return Observable.forkJoin(
this.teamsService.getTeam(this.zone['TeamId']),
this.zonesService.getZoneAssociations(this.zone['id'], '/myDevices'),
this.zonesService.getZoneAssociations(this.zone['id'], '/devices'),
this.zonesService.getZoneAssociations(this.zone['id'], '/groupMembers'),
this.sitesService.getSite(this.zone['SiteId'])
);
})
.subscribe(
_data => {
// data handling...
},
_error => {
// error handling ...
}
);
}
我尝试修复:
private getZone() {
this.spinner.show();
this.zonesService.getZone(this.zoneId)
.map(response => {
this.zone = response['group'];
return this.zone;
})
.flatMap(() => {
return Observable.forkJoin(
this.teamsService.getTeam(this.zone['TeamId']),
this.zonesService.getZoneAssociations(this.zone['id'], '/myDevices'),
this.zonesService.getZoneAssociations(this.zone['id'], '/devices')
.catch(error => Observable.throw(error)),
this.zonesService.getZoneAssociations(this.zone['id'], '/groupMembers')
.catch(error => Observable.throw(error)),
this.sitesService.getSite(this.zone['SiteId'])
);
})
.subscribe(
_data => {
// data handling...
},
_error => {
// error handling...
}
);
}
最佳答案
返回 Observable.throw
只会重新抛出捕获的错误,这将看到 forkJoin
发出错误。
相反,您可以使用 Observable.of(null)
发出 null
然后完成,这将看到 forkJoin
发出一个 null
用于发出错误的可观察对象:
return Observable.forkJoin(
this.teamsService.getTeam(this.zone['TeamId']),
this.zonesService.getZoneAssociations(this.zone['id'], '/myDevices'),
this.zonesService.getZoneAssociations(this.zone['id'], '/devices')
.catch(error => Observable.of(null)),
this.zonesService.getZoneAssociations(this.zone['id'], '/groupMembers')
.catch(error => Observable.of(null)),
this.sitesService.getSite(this.zone['SiteId'])
);
或者,如果您想将错误作为一个值发出,您可以使用 Observable.of(error)
。
关于javascript - Observable - 401 导致 forkJoin 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45086867/