Aar*_*ron 5 javascript fork-join observable rxjs angular
我正在使用 forkJoin 发出多个服务器请求。这是我在整个应用程序中经常使用的一种模式,并且效果很好。然而,我们刚刚开始实现在后端完成的用户角色。我不确定实现角色的最佳实践是什么,因为我主要是前端开发人员,但这是我遇到的问题:
我们的应用程序具有成员和管理员成员角色。
从每个视图中,我都必须为成员和管理员成员角色调用后端,而不管角色是否在前端确定。
由于成员和管理员成员都拥有个人数据,因此始终为这两个角色返回成员数据。
仅当用户是管理员时才返回对管理员数据的请求。每当用户没有管理员访问权限时,请求都会返回 401 错误。这是我遇到问题的地方。
每当调用返回 401 时,就会调用我的 subscribe 方法中的错误方法,而我无权访问所进行的任何调用,包括与成员数据关联的调用。
在我包含在 forkJoin 中的代码中,有五个调用传递到该方法中。如果用户是管理员,则第三次和第四次调用仅返回数据,而其余调用始终为成员或管理员返回。
当用户不是管理员时,第三次调用返回 401,流停止并调用我的 subscribe 方法中的错误处理程序。这显然不是我想要的。我希望流继续,以便我可以使用 _data 方法中的数据。
我只使用了 6 个月的 RXJS 并且正在学习。也许我应该使用不同的模式,或者有办法解决这个问题。任何有关代码示例的帮助将不胜感激。在我的代码示例下方,我包含了另一个代码示例,其中我尝试通过使用 catch 方法来解决问题。它没有用。
我的视图获取方法:
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 ...
}
);
}
Run Code Online (Sandbox Code Playgroud)
我试图修复:
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...
}
);
}
Run Code Online (Sandbox Code Playgroud)
返回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'])
);
Run Code Online (Sandbox Code Playgroud)
或者,如果您想将错误作为值发出,您可以使用Observable.of(error).
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |