xRay
xRay

Reputation: 801

User gets always redirected

I would like to redirect the user to the homepage if there is no cookie set.

This is what I have tried:

app-routing.modules.ts

const routes: Routes = [
  { path: 'search', component: SearchComponent, canActivate: [LoginGuard] }
];

login.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {SearchComponent} from '../search/search/search.component';

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {
  constructor(private searchComponent: SearchComponent) {
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): any {
      this.searchComponent.hasAccess().then(result => {
        return result;
      });
    }
}

search.components.ts

hasAccess() {
  return new Promise(resolve => {
    this.login.hasCookie(this.cookieService.get('login')).subscribe(hasCookie => {
      if (hasCookie === 1) {
        return new Promise(() => {
          this.login.getCookie().subscribe(cookieFromServer => {
            if (cookieFromServer === this.cookieService.get('login')) {
              return resolve(true);
            } else {
              return resolve(false);
            }
          });
        });
      }
      return resolve(false);
    });
  });
}

The output of result is either true or false (I have tested both of them). No matter if it's true or false, the user gets ALWAYS redirected.

If I replace

this.searchComponent.hasAccess().then(result => {
  return result;
});

with return true, then it works and the user will not be redirected.

Why would return true; work but not return result;?

Upvotes: 0

Views: 51

Answers (1)

Ninad
Ninad

Reputation: 433

I think problem is with your canActivate method as it does not return anything. Just by adding return to this.searchComponent.hasAccess() should solve your problem. Your code can be like this:

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): any {
      return this.searchComponent.hasAccess().then(result => {
        return result;
      });
    }

After this angular will know to wait till promise gets resolved.

Upvotes: 1

Related Questions