简体   繁体   中英

Typescript bool value returns “undefined”

I have two typescripts files, one admin.guard.ts and another user.services.ts. I am trying to guard a component from being accessible by storing a user boolean value in user.services.ts file. However, when trying to access this bool value, I receive an undefined console log. I set this boolean value from a user component, when setting it through "setAdmin()" method, it immediately logs to console with proper value. It just seems like by calling this value from "admin.guard.ts" file, its returning "undefined".

Any help would be appreciated, thanks.

// User.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';

import { environment } from '../../environments/environment';
import { User } from './user.model';

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

  public isAdmin!: boolean;

  constructor(private http: HttpClient) { }

  setAdmin(_value: boolean){
    this.isAdmin = _value;
    console.log(this.isAdmin);  // THIS LOGS THE CORRECT ISADMIN BOOL VALUE THAT ITS SET TO
  }

  isAdminUser(){
    return this.isAdmin;
  }

}


// Admin.guard.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AdminGuard implements CanActivate {

  constructor(private userService: UserService, private router: Router){}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    console.log(this.userService.isAdminUser());  // THIS LOGS UNDEFINED
    if(this.userService.isAdminUser())
      return true;
    return false;
  }
  
}

// User-profile.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../shared/user.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnInit {

  userDetails: any;

  constructor(private userService: UserService, private router: Router) { }

  ngOnInit(): void {
    this.userService.getUserProfile().subscribe(
      res=> {
        this.userDetails = res['user'];
        if(this.userDetails.role === "admin")
          this.userService.setAdmin(true);
        else
          this.userService.setAdmin(false);
      },
      err =>{
        console.log(err);
      }
    );
  }

  onLogout(){
    this.userService.deleteToken();
    this.router.navigate(['login']);
  }

}


You should use relay subject.

Something like this:

import { ReplaySubject } from 'rxjs/ReplaySubject'

@Injectable()
export class AdminGuard  {
 

  isAdmin = new ReplaySubject(0);
  updateisAdmin(value) {
      this.isAdmin.next(value);
  }


}

And in the other service or component:

this.AdminGuard.updateisAdmin(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM