Igor
Igor

Reputation: 277

Returning value from BehaviorSubject in angular 6 guard

I'm going this direction because i've another guard who is validating the user on the token previously stored. This is what i was doing in previous version of rxjs, now in the latest you cant map on the subject.

canActivate(next: ActivatedRouteSnapshot,
           state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.authservice.behaviorsubject().map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  })
}

I need any guidence how to get this thing working. I've tried somting like this but wont return anything since never subscribed to it (and also its not a Observable its a AnonymusSubject when i console.log it)

canActivate(next: ActivatedRouteSnapshot,
           state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.authservice.behaviorsubject().pipe(
    map(x => {
      if (x) {
        return true;
      } else {
        return false;
      }
    })
  )
}

Also tried converting it into observable with Observable.create() but wont work. I know im missing something. Heeeeelp :)

Upvotes: 0

Views: 4258

Answers (1)

J. Pinxten
J. Pinxten

Reputation: 307

return your behaviorSubject as an observable in your authservice:

private _authed: BehaviorSubject<boolean> = new BehaviorSubject(null);

behaviorsubject():Observable<boolean> {
   return this._authed.asObservable()
}

Also a small comment: CanActivate works with observables, so if your behaviorsubject function returns a Observable with type boolean, you don't need to map it

Upvotes: 1

Related Questions