【问题标题】:Angular router does not navigate to set url but to empty url pathAngular 路由器不会导航到设置 url,而是导航到空 url 路径
【发布时间】:2020-07-20 18:12:44
【问题描述】:

我目前正在使用其路由器功能开发一个 Angular 应用程序。所有路由似乎都运行良好,直到我发现成功登录后,我设置的 url 路径,即“/admin”将不会被遵循,路由器默认为“/”。这是代码:

//login.component.ts
if (this.authService.getUserRole() == 'user' || 'agent') {
window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
window.location.assign('/admin')
}



//app.routing.ts
import {AdminComponent} from './admin-master/admin/admin.component;
import {HomeComponent} from './home/home.component;

const appRoutes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: {permission:{only: ['admin']}}}
]

编辑:(添加 auth.guard.ts)

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

      const permission = next.data["permission"];

      if(this.authService.isLoggedIn() &&
      permission.only.includes(this.authService.getUserRole())) {
        return true;
      } else {
        this.router.navigateByUrl('/logout');
      }
    
  }
  
}

问题:

  1. 虽然已经成功登录,但路由器会将用户重定向到一个空白 url,而不是我在 login.component.ts 文件夹中专门提供的设置 URL。

  2. 因为它会重定向到一个空的 URL,home.component.html 中的元素也会显示在我的管理仪表板中,这是我不希望发生的。

总之,如何正确路由以下函数?难道我做错了什么? 感谢您的帮助!

【问题讨论】:

  • 您在浏览器控制台中看到了什么 (F12)
  • @Pieterjan 这就是我的路由器事件中立即显示的内容:导航开始:NavigationStart(id: 1, url: '/')
  • 您的AuthGuard 是什么样的?此外,您的路由对我来说看起来有点奇怪,您没有使用路由功能中的角度构建 (angular.io/guide/router) 而不是window.location.assign('/admin'),您应该使用this.router.navigate(['admin'], { relativeTo: this.route });
  • 我将编辑我的帖子以添加 AuthGuard!另外,我使用window.location.assign 的原因是为了让浏览器认为我已经重定向到该路由。这是因为我的某些功能只有在我刷新应用程序时才会加载。
  • @Pieterjan 有什么想法吗?

标签: angular typescript angular-routing


【解决方案1】:

您可以使用Router 而不是window.location.assign 导航到不同的网址

例子:

import { Router} from '@angular/router';

/* Login Component */

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

navigate() {
    if (this.authService.getUserRole() == 'user' || 'agent') {
        this.router.navigateByUrl('/')
    } else if (this.authService.getUserRole() == 'admin') {
        this.router.navigateByUrl('/admin')
    }
}

查看文档https://angular.io/api/router/Router

【讨论】:

  • 我以前试过这个,但是虽然登录成功,但它仍然没有导航到我想要的路线。我使用 window.location.assign 的原因是为了欺骗浏览器并加载我导航到的新组件。
  • 这是您应该能够使用的代码。我的印象是您要导航到的 URL 不存在。通常,您会在浏览器控制台中收到包含更多信息的错误。
【解决方案2】:

替换window.location.assign('/admin')

this.router.navigate([‘../admin’], {relativeTo: this.route});

路由器:路由器 路线:激活路线

我希望这是你想要的。

【讨论】:

  • 您能提供如何将路由器添加到构造函数中吗?似乎无法复制您的解决方案。
  • 注入路由器就像你激活路由一样
【解决方案3】:

您确定要导航到管理页面吗? 我认为你的代码看起来不对。

if (this.authService.getUserRole() == 'user' || 'agent') {
    window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
    window.location.assign('/admin')
}

应该像下面这样,否则第一个总是正确的,因为|| 'agent'

const role = this.authService.getUserRole();
if (role  === 'user' || role === 'agent') {
    window.location.assign('/')
} else if (role  === 'admin') {
    window.location.assign('/admin')
}

我更喜欢 === 进行值和类型检查。

【讨论】:

  • 感谢您指出我的一个错误。 || role === 'agent' 应该是正确的代码。尽管如此,我已经找到了我的问题的答案。我会尽快发布答案!
【解决方案4】:

在我的app.routing.ts 文件中,我观察到从下面的代码中删除{useHash: true} 会导致正确的URL 重定向。这是因为添加{useHash: true} 会在我的网址中添加一个额外的/#,导致默认为空白网址,因为它不匹配任何路由。

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash: true, enableTracing: true });

我已将其修改为:

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

注意:我还删除了 enableTracing: true,只是为了清理我的控制台结果。

【讨论】:

    猜你喜欢
    • 2017-09-09
    • 2017-10-10
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多