简体   繁体   English

角路由重定向到父路由,而不是页面刷新中的子路由

[英]Angular routing redirects to parent route instead of child on page refresh

I have the following app routing: 我有以下应用程序路由:

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children:
      [
        {
          path: '',
          redirectTo: '/dashboard',
          pathMatch: 'full'
        },
        {
          path: 'dashboard',
          component: DashboardComponent,
          children:
            [
              {path: 'profile', component: ProfileComponent},
              {path: 'user-management', component: UserManagementComponent},
              {path: 'role-management', component: RoleManagementComponent}
            ]
        }
      ]
  },
  {path: 'login', component: LoginComponent},
  {path:'token-verify',component:TwoFactorVerificationComponent}
];

So here is my problem .Let's say I am on route dashboard .Navigating to /profile or /user-management works fine using the angular router.However I am facing the following problem If I am on route /dashboard/user-management or /dashboard/role-management and do a page refresh I will get redirected to /dashboard/profile . 所以这是我的问题。假设我在路线dashboard使用角路由器导航到/profile/user-management效果很好,但是如果我在路线/dashboard/user-management/dashboard/role-management上则遇到以下问题/dashboard/role-management并刷新页面,我将重定向到/dashboard/profile Any ideas what I am doing wrong? 有什么想法我做错了吗?

Here is my auth quard 这是我的身份验证

import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from "@angular/router";
import { Observable } from "rxjs";
import { UserService } from "../services/user.service";
import { TokenService } from "../services/token.service";

@Injectable({
  providedIn: "root"
})
export class AuthGuard implements CanActivate {
  constructor(
    private tokenService: TokenService,
    private userService: UserService
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    console.log(`Requested -> state: ${state.url}`);
    if (this.tokenService.isLoggedIn()) {
      console.log("isLogged in and will return true");
      return true;
    } else {
      console.log("will fail and go to login");
      this.userService.redirectToLogginPage();
      return false;
    }
  }
}

Whenever I do refresh the page the auth guard gets called and it prints 每当我刷新页面时,就会调用身份验证保护并打印

Requested -> state: /dashboard/user-management 
auth.guard.ts:26 isLogged in and will return true

in case I am logged in 万一我登录

After some digging I found that If I refresh the page on dashboard/user-management the OnInit method of that component is actually called but I get redirected in /dashboard/profile 经过一番挖掘后,我发现如果刷新dashboard/user-management上的页面,则实际上会调用该组件的OnInit方法,但会在/dashboard/profile重定向

   const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children:
      [
        {
          path: '',
          redirectTo: '/dashboard',
          pathMatch: 'full'
        },
        {
          path: 'dashboard',
          component: DashboardComponent,
 children: [
                  {path: '', redirectTo: 'profile'},
                  {path: 'profile', component: ProfileComponent},
                  {path: 'user-management', component: 
                UserManagementComponent},
                  {path: 'role-management', component: 
                   RoleManagementComponent}
              ]     
   }
      ]
  },
  {path: 'login', component: LoginComponent},
  {path:'token-verify',component:TwoFactorVerificationComponent}
];

So I finally found what was wrong.In the dashboard component (the parent one) this was happening on ngOnInit() 所以我终于找到了问题所在。在仪表板组件(父组件)中,这发生在ngOnInit()上

ngOnInit() {
    // @TODO
    // refactor using async await
    this.userService
      .getProfile()
      .then((res: any) => {
        console.log(res);
        const user: UserIdentity = res;
        this.user_email = user.emailId;
        if (this.userService.checkrole(user.roles, "ADMIN")) {
          //this.router.navigate(['/dashboard']);
        }
      })
      .catch(error => {
        console.error(error);
      });
  }

I removed this line and it worked.The reasonn is that after the child view was rendered the parent view would say "Hey child view go back to the parent view" 我删除了这一行,它起作用了。原因是在渲染子视图之后,父视图会显示“嘿,子视图返回到父视图”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 路由:每当我刷新页面或手动键入特定的 URL 时,Angular 都会重定向回父路由 - Angular Routing: Angular redirects back to the parent route whenever I refresh the page or manually type specific URL 在页面刷新时重定向到父路由而不是子路由 - Redirection to parent route instead of child on page refresh Angular 在子路由上刷新页面 - Angular page refresh on child route 刷新当前路径将重定向到父路径,而不是在Angular 5中 - Refreshing the current route redirects to parent route instead in Angular 5 Angular 2子路由是否会刷新父路由 - Will Angular 2 child routes refresh the parent route Angular2子组件浏览器刷新重定向到父组件 - Angular2 Child Component browser refresh redirects to Parent Component 角路由器。导航到子重定向到404路由 - Angular router.navigate to child redirects to 404 route instead 角度路由 - 在路由到子节点时,视图仅在刷新页面时更新 - Angular routing - On routing to a child, View updates only on refresh of the page Angular2 路由,父子节点——路由组件 vs 视图组件 - Angular2 routing, parent child -- route component vs view component 角度子路由加载父组件而不是子组件 - Angular child route loading parent instead of child component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM