简体   繁体   中英

Angular 6+ Guards - Return true/false to combineLatest subscription

How can I return true/false inside subscribe ?

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

}

You simply don't subscribe to your observable.

You should always return an Observable for the next chain operator which is guard in this case.

Delete subscribe((data) => {...}) part.

If you have to apply a custom logic, do it within map operator and return whatever you want to return ie true or false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM