我在访问我的角度组件内的服务变量值时遇到问题。Navbar 组件将用户设置为在服务内登录,并且路由保护负责启用子路由,但路由保护无法获取 userStatus 的更新值
import { Component, OnInit } from '@angular/core';
import { UserDetailsService } from '../user-details.service.js';
import { Router } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
UserStatus: boolean;
constructor( private UserService: UserDetailsService, private router: Router) { }
ngOnInit() {
this.UserService.UserStatus.subscribe((data: boolean) => {
this.UserStatus = data;
});
this.UserService.getUserStatus();
}
logout() {
this.UserService.UpdateStatus(false);
this.router.navigate(['login']);
}
login() {
this.UserService.UpdateStatus(true);
this.router.navigate(['home/products']);
}
}
路由保护组件
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, CanActivateChild} from '@angular/router';
import { Observable } from 'rxjs';
import { UserDetailsService } from './user-details.service.js';
@Injectable({
providedIn: 'root'
})
export class LoginGuardGuard implements CanActivateChild, CanActivate {
constructor(private userDetails: UserDetailsService, private router: Router) {}
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.userDetails.getUserStatus()) {
return true;
} else {
this.router.navigate(['login']);
// return false;
}
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.userDetails.getUserStatus()) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
}
}