Home > Net >  canLoad guard doesn't get the updated value
canLoad guard doesn't get the updated value

Time:10-12

UPD. Solved. I was using 2 instanses of a service and it caused problems

I'm stuck with canLoad guard. When i push a button in component I want to change the false value in service and let my Guard to load a module. But guard only receives a false value. How can I make it work and see when I update value in service? It looks like it doesn't see when value is changed and triggers before i update it

Here is my AuthGuard

import { Injectable } from '@angular/core';
import { CanLoad } from '@angular/router';

import { AuthenticationService } from '../services/auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanLoad {
 
    constructor(private authService: AuthenticationService) {}
    canLoad(): boolean {
       if (this.authService.isLogged()) {
            return true;
       } else {
           return false;
       }
      
    }
    
}

My AuthService

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {

    private isUserLoggedIn = new BehaviorSubject(false);
    
    isLogged() {
        console.log(this.isUserLoggedIn.value); // <--- FALSE
        return this.isUserLoggedIn.value;
    }

    login() {
        this.isUserLoggedIn.next(true);
        console.log(this.isUserLoggedIn.value); // <--- TRUE
    }
}

Routing:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './guards/auth.guard';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'login'
  },
  {
    path: 'dashboard',
    loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
    canLoad: [AuthGuard]
  },
  {
    path: 'login',
    loadChildren: () => import('./modules/login/login.module').then(m => m.LoginModule)
  },
  {
    path: '**',
    redirectTo: 'dashboard'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Main Module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from './guards/auth.guard';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

Login Module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { NzFormModule } from 'ng-zorro-antd/form';
import { LoginRoutingModule } from './login-routing.module';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { AuthenticationService } from 'src/app/services/auth.service';
@NgModule({
  declarations: [
    LoginComponent
  ],
  imports: [
    CommonModule,
    NzFormModule,
    LoginRoutingModule,
    NzInputModule,
    NzButtonModule
  ],
  providers: [
    AuthenticationService
  ]
})
export class LoginModule { }

Login Routing module

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginComponent } from './login.component';

const routes: Routes = [
    {
        path: '',
        pathMatch: 'full',
        component: LoginComponent
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
  })
  export class LoginRoutingModule {}

Button

<button (click)="submitForm()">pressme</button>

 submitForm() {
    this.authService.login(); 
    this.router.navigate(['dashboard']);
  }

CodePudding user response:

The canLoad() will only receive the value on first tentative to access the component. Once the login() is done try to navigate to the component/page you want to load and it should work.

Also, removing private to your BehaviorSubject might help?

CodePudding user response:

Maybe using observable will do the trick:

@Injectable({ providedIn: 'root' })
export class AuthenticationService {

    private isUserLoggedIn = new BehaviorSubject(false);
    public isUserLoggedIn$: Observable<boolean>

    constructor(){
      this.isUserLoggedIn$ = this.isUserLoggedIn.asObservable();
    }

    login() {
        this.isUserLoggedIn.next(true);
    }
}



@Injectable()
export class AuthGuard  implements CanLoad {
  constructor(private authService: AuthenticationService) {}

canLoad(route: Route,segments: UrlSegment[]): boolean|UrlTree|Observable<boolean|UrlTree>|Promise<boolean|UrlTree> {
  return this.authService.isUserLoggedIn$;  
}

}
  • Related