0

我在访问我的角度组件内的服务变量值时遇到问题。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;
      }
  }
}
4

1 回答 1

2

发生这种情况是因为在您的app-navbar组件route-guard中,您已经导入了带有js扩展名的服务,该扩展名与 angular 中的单例服务模型相反。

由于 .js 扩展名,转译器将它们识别为两个独立的实例。

所以改变进口

import { UserDetailsService } from '../user-details.service.js';

import { UserDetailsService } from '../user-details.service';

应该解决这个问题。

于 2021-09-03T18:14:46.973 回答