简体   繁体   English

基于角色的Angular 4路由默认页面

[英]Angular 4 routing default page based on role

I have defined my routes as below:我已经定义了我的路线如下:

const appRoutes: Routes = [
 {
  path: 'teacher',
  component: 'TeacherComponent'
 },
{
  path: 'student',
  loadChildren: './components/student/student.module#StudentModule',
  canLoad: [AuthGuard]
},
{ path: '**',   redirectTo: '/' }
];

I want to route my default routing based on the loggedIn user role.我想根据登录用户角色路由我的默认路由。 If it's student, I want to default my path: '**' to be redirected to '/student'.如果是学生,我想默认我的路径:'**' 被重定向到 '/student'。 Similarly for Teacher role I wanted it to default to '/teacher'.同样,对于教师角色,我希望它默认为“/teacher”。 How to implement this role based navigation by defaulting route to different urls based on the role?如何通过基于角色默认路由到不同的 url 来实现这个基于角色的导航?

You can use a route resolver.您可以使用路由解析器。

Here is one of mine:这是我的一个:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Observable } from 'rxjs/Observable';

import { IMovie } from './movie';
import { MovieService } from './movie.service';

@Injectable()
export class MovieResolver implements Resolve<IMovie> {

    constructor(private movieService: MovieService) { }

    resolve(route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<IMovie> {
        const id = route.paramMap.get('id');
        return this.movieService.getMovie(+id);
    }
}

This code will prevent the route from continuing until the movie is retrieved.此代码将阻止路由继续,直到检索到电影为止。

You could do something similar to retrieve your roles.您可以执行类似的操作来检索您的角色。 Then instead of simply returning, you could use the data you retrieved to activate different routes depending on the user's role.然后,您可以使用检索到的数据根据​​用户的角色激活不同的路由,而不是简单地返回。

{ path: "", component: LoginViewComponent, pathMatch: "full",canActivate:[AuthGuard] }

    @Injectable()
export class AuthGuard implements CanActivate {
  role: string = "A";

  constructor(private router: Router) {}

  canActivate() {
    const route = this.role === "A" ? "/home" : "/catalog";
    this.router.navigate(['/home']);
    return true;
  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM