[英]Typescript bool value returns “undefined”
我有兩個打字稿文件,一個 admin.guard.ts 和另一個 user.services.ts。 我試圖通過在 user.services.ts 文件中存儲用戶布爾值來保護組件不被訪問。 但是,當嘗試訪問這個 bool 值時,我收到了一個未定義的控制台日志。 我從用戶組件設置了這個布爾值,當通過“setAdmin()”方法設置它時,它會立即以正確的值登錄到控制台。 似乎通過從“admin.guard.ts”文件調用這個值,它返回“undefined”。
任何幫助將不勝感激,謝謝。
// 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']);
}
}
你應該使用中繼主題。
像這樣的東西:
import { ReplaySubject } from 'rxjs/ReplaySubject'
@Injectable()
export class AdminGuard {
isAdmin = new ReplaySubject(0);
updateisAdmin(value) {
this.isAdmin.next(value);
}
}
在其他服務或組件中:
this.AdminGuard.updateisAdmin(false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.