Angular 6+ Guards-返回true / false以合并最新订阅

时间:2018-08-14 06:01:28

标签: angular rxjs rxjs6 angular-guards

如何在subscribe内部返回true / false?

import {Injectable} from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {AppState} from '../../app.state';
import {select, Store} from '@ngrx/store';
import {merge, combineLatest} from 'rxjs';
import {map, take, tap} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';


@Injectable()
export class PermissionsGuard implements CanActivate {

user;

constructor(
  private router: Router,
  private store: Store<AppState>
) {
}

canActivate(route: ActivatedRouteSnapshot): any {

  const academy$ = this.store.pipe(select(state => state.academy));
  const user$ = this.store.pipe(select(state => state.user));

  return combineLatest(
     academy$,
     user$
  ).pipe(
     map((data) => {
        console.log(data[0]);
        console.log(data[1]);
        return data;
     })
  ).subscribe((data) => {
     console.log(data);
     // return true or false to guard
  })
}

}

1 个答案:

答案 0 :(得分:1)

您只是不订阅可观察的内容。

在这种情况下,您应始终为下一个链式运算符返回一个Observable。

删除subscribe((data) => {...})部分。

如果您必须应用自定义逻辑,请在map运算符中执行此操作,然后返回要返回的内容,即truefalse