2017-07-13 53 views
2

我正在使用forkJoin发出多个服务器请求。这是我通常在应用程序中使用的一种模式,它一直在运行良好。然而,我们刚刚开始实现在后端完成的用户角色。我不确定实施角色的最佳做法是什么,因为我主要是前端开发人员,但这是我遇到的问题:Observable - 401导致forkJoin出错

我们的应用程序具有成员和管理成员角色。

  1. 从每个视图我必须调用成员和管理成员角色的后端,而不管角色是否在前端确定。

  2. 由于成员和管理员都拥有个人数据,所以会员数据总是返回给两个角色。

  3. 仅当用户是管理员时才会返回管理员数据的请求。只要用户没有管理员权限,该请求就会返回401错误。这是我遇到问题的地方。

每当调用返回一个401错误的方法在我的订阅方法被调用,我不访问任何所做的包括相关的成员数据呼叫的呼叫。

在forkJoin中包含的代码中,有五个调用传入该方法。如果用户是管理员,则第三次和第四次调用仅返回数据,而其余的调用总是返回给成员或管理员。

当用户不是管理员时,第三次调用返回401,流停止,并调用我的订阅方法中的错误处理程序。这显然不是我想要的。我希望这个流继续下去,这样我就可以在_data方法中使用这些数据。

我只使用RXJS 6个月,正在学习。也许我应该使用不同的模式,或者有办法解决这个问题。任何帮助代码示例将不胜感激。在我的代码示例下面,我包含了另一个代码示例,我试图通过使用catch方法来解决问题。它没有工作。

我查看get方法:

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... 
     } 
    ); 
} 

回答

0

返回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)

+0

谢谢。这真棒,它完美运作。 – Aaron