user13457337
user13457337

Reputation:

Angular v12, why the routing guard does not work as expected?


auth.service.ts
  get(): Observable<HttpResponse<any>> {
    return this.http.get<any>(urls.angular.signin_guard, authOptions);
  }


auth.guard.ts
  checkAuth(): true | UrlTree {
    this.auth.get().subscribe(
      () => {
        return true;
      }
    );
    return this.router.parseUrl('/account/signin');
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): true | UrlTree {
    return this.checkAuth();
  }


router.ts
  {
    path: 'account', canActivateChild: [AuthGuard], children: [
      {path: 'me', component: MeComponent}
    ]
  },

auth.service.ts => check if the user is signed in

auth.guard.ts => if the user is already signed in, return true, others will jump to the sign in page

Upvotes: 0

Views: 140

Answers (1)

Stavm
Stavm

Reputation: 8131

You should return an observable. something like:

  checkAuth(): Observable<boolean| UrlTree> {
    return this.auth.get().pipe(
      mapTo(true),
      catchError((e) => of(this.router.parseUrl('/account/signin')))
    )
  }

Upvotes: 1

Related Questions