简体   繁体   English

Typescript bool 值返回“未定义”

[英]Typescript bool value returns “undefined”

I have two typescripts files, one admin.guard.ts and another user.services.ts.我有两个打字稿文件,一个 admin.guard.ts 和另一个 user.services.ts。 I am trying to guard a component from being accessible by storing a user boolean value in user.services.ts file.我试图通过在 user.services.ts 文件中存储用户布尔值来保护组件不被访问。 However, when trying to access this bool value, I receive an undefined console log.但是,当尝试访问这个 bool 值时,我收到了一个未定义的控制台日志。 I set this boolean value from a user component, when setting it through "setAdmin()" method, it immediately logs to console with proper value.我从用户组件设置了这个布尔值,当通过“setAdmin()”方法设置它时,它会立即以正确的值登录到控制台。 It just seems like by calling this value from "admin.guard.ts" file, its returning "undefined".似乎通过从“admin.guard.ts”文件调用这个值,它返回“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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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