【问题标题】:Problem of ending return statement on canActivate在canActivate上结束return语句的问题
【发布时间】:2021-07-09 13:58:51
【问题描述】:

我在使用CanActivate方法时出现问题:出现error ts2366 "Function lacks ending return statement and return type does not include undefined"。

按照我的代码:

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

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      this.router.navigate(['/auth']);
    }
  }
}

我尝试添加 '| undefined' 在布尔值之后,但另一个错误告诉我它与 CanActivate 不兼容。

你有什么解决办法吗?

提前感谢您的帮助。

【问题讨论】:

  • 您应该从canActivate 返回booleanUrlTree。如果您返回 UrlTree,它将为您处理导航,因此您无需自己调用this.router.navigate(请参阅angular.io/api/router/CanActivate
  • @cdimitroulas 所以,如果我理解的话,我需要在第二种情况下返回一个 this.router.parseUrl('/auth') 并且导航将使用这个 UrlTree 自动完成?
  • 我相信是这样 - 我实际上并没有使用过 Angular,所以我根据我在之前评论中发送的文档链接中所写的内容。
  • @cdimitroulas 谢谢你的回答,已经解决了。
  • 我将为您的问题添加一个正确答案 - 如果您能将其标记为正确答案,我将不胜感激:)

标签: angular typescript canactivate


【解决方案1】:

您应该从canActivate 返回booleanUrlTree。如果您返回UrlTree,它将为您处理导航,因此您无需自己调用this.router.navigate(参见https://angular.io/api/router/CanActivate

您的代码可能如下所示:

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

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      return this.router.parseUrl('/auth');
    }
  }
}

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2019-06-19
    • 2013-06-14
    • 1970-01-01
    • 2010-12-09
    • 2018-03-03
    • 2018-10-28
    • 2015-08-03
    • 2019-05-28
    相关资源
    最近更新 更多