3

RxJS 新手在这里。使用 Angular 6。试图弄清楚如何Observable<T>Observable<Observable<T>>. 不确定这是否有效并且难以从概念上理解它,但这似乎是一个简单的问题。

我研究了 switchMap、flatMap、forJoin,但我认为它们不符合我的需求。

我正在尝试做的是一个 Angular 路由保护,它将阻止用户访问路由,除非他们拥有必要的权限。2个依赖项是一个用户配置文件,用于获取他们的信息,然后用于获取他们的权限。这种混合导致了 Observable 的 Observable 问题。这是我所拥有的:

export class AuthPermissionsRouteGuard implements CanActivate {
    constructor(
    private router: Router,
    private authService: AuthPermissionsService,
    private openIdService: AuthOpenIdService) {}

    /**Navigates to route if user has necessary permission, navigates to '/forbidden' otherwise */
    canActivate(routeSnapshot: ActivatedRouteSnapshot): Observable<boolean> {
        return this.canNavigateToRoute(routeSnapshot.data['permissionId'] as number);
    }

    /**Waits on a valid user profile, once we get one - checks permissions */
    private canNavigateToRoute(permissionId: number): Observable<boolean> {
        const observableOfObservable = this.openIdService.$userProfile
            .pipe(
                filter(userProfile => userProfile ? true : false),
                map(_ => this.hasPermissionObservable(permissionId)));

            // Type Observable<Observable<T>> is not assignable to Observable<T> :(
        return observableOfObservable;
    }

    /**Checks if user has permission to access desired route and returns the result. Navigates to '/forbidden' if no permissions */
    private hasPermissionObservable(permissionId: number): Observable<boolean> {
        return this.permissionsService.hasPermission(permissionId).pipe(
            map(hasPermission => {
                if (!hasPermission) {
                    this.router.navigate(['/forbidden']);
                }

                return hasPermission;
            }
        ));
    }
}

非常感谢!!

4

1 回答 1

3

就目前而言,您正在从函数返回一个 Observable hasPermissionObservable,它将被包装在来自map operator.

你会想看看mergeMap/flatMap operatoror contactMap operator

MergeMap:当您希望展平内部 observable 但想要手动控制内部订阅的数量时,最好使用此运算符。Learn RXJS 链接中的示例:

// RxJS v6+
import { of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

// emit 'Hello'
const source = of('Hello');
// map to inner observable and flatten
const example = source.pipe(mergeMap(val => of(`${val} World!`)));
// output: 'Hello World!'
const subscribe = example.subscribe(val => console.log(val));

ContactMap:将值映射到内部 observable,按顺序订阅和发出。Learn RXJS 链接中的示例:

// RxJS v6+
import { of } from 'rxjs';
import { concatMap } from 'rxjs/operators';

// emit 'Hello' and 'Goodbye'
const source = of('Hello', 'Goodbye');
// example with promise
const examplePromise = val => new Promise(resolve => resolve(`${val} World!`));
// map value from source into inner observable, when complete emit result and move to next
const example = source.pipe(concatMap(val => examplePromise(val)));
// output: 'Example w/ Promise: 'Hello World', Example w/ Promise: 'Goodbye World'
const subscribe = example.subscribe(val =>
  console.log('Example w/ Promise:', val)
);

所以对于你的例子:

/**Waits on a valid user profile, once we get one - checks permissions */
private canNavigateToRoute(permissionId: number): Observable<boolean> {
  const observableOfObservable = this.openIdService.$userProfile
    .pipe(
       filter(userProfile => userProfile ? true : false),
       concatMap(_ => this.hasPermissionObservable(permissionId))); // <- try changes here

  // Type Observable<Observable<T>> is not assignable to Observable<T> :(
  return observableOfObservable;
}
于 2019-04-03T01:04:50.280 回答