0

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

}
Michalis
  • 6,686
  • 13
  • 52
  • 78

1 Answers1

1

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 i.e. true or false

Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
  • You are right... but now I can't figure out why data[0] doesn't have value... It's null... It doesn't wait ngrx to fill the value.... When I was using subscribe I was taking the correct value... – Michalis Aug 14 '18 at 06:09
  • Try to use `take(1)` or `first()` operator within `pipe` after `map` – Bunyamin Coskuner Aug 14 '18 at 06:14
  • I found that my problem is that I'm using a dispatch event inside a guard that is async... So the guard doesn't wait for the async effect to finish before continue. Any advice? – Michalis Aug 14 '18 at 06:39