当用户id更改时,订阅将随机运行。有时,我不这样做。UsRID变量来自下拉选择器(选择库)。
即使userid是唯一更改的流,订阅也不应该一直运行吗?
有没有什么明显的迹象表明我正在崩溃或做错了?
this.singleUserControl.valueChanges
.mergeMap((userId: number) => {
this.router.navigate([ '/r', 'company-admin', 'user-claims', userId.toString() ]);
this.userRoles = [];
this.claims = [];
const userRolesObserv: Observable<Array<RoleWithClaims>> =
this.claimsService.getUserRoles(userId)
.mergeMap((roles: Array<Role>) => {
const roleObservables = [];
for (const role of roles) {
roleObservables.push(this.claimsService.getClaimsForRole(role.id)
.mapTo(claims => ({
role: role,
claims: claims,
} as RoleWithClaims)));
}
return forkJoin(roleObservables);
});
return forkJoin([
Observable.of(userId),
userRolesObserv,
this.claimsService.getAllClaimsForUser(userId),
]);
})
.subscribe((data: [ number, Array<RoleWithClaims>, Array<Claim>]) => {
this.userSelectedId = data[0];
this.userRoles = data[1]
this.claims = data[2];
}, (error) => {
console.log(error);
});
最佳答案
尝试这样做:
return (roleObservables.length) ? forkJoin(roleObservables) : Observable.of([]);
forkjoin不会以空数组发出,因此在这段代码中,不会对没有关联角色的任何用户id执行订阅。
在我所有的RX项目中,我都有一个实用功能:
emptyJoin(obs: Observable<any>[]): Observable<any[]> => (obs.length) ? forkJoin(obs) : Observable.of([]);