基于angular8中的条件进行路由

时间:2019-06-26 11:45:40

标签: angular angular8

我正在尝试将路由实现为-在gsearch中为router-outlet具有'name'。当gsearch条件匹配<router-outlet name="gsearch"></router-outlet>时应打开视图,其余router-outlet不应显示任何视图。

根据路由条件,“ gsearch”路由出口或其他路由器出口应同时工作。

如何实现这一目标?

app.component.html

// if, else if, else conditions type

<router-outlet name="gsearch"></router-outlet> <=== gSearch opens here
<router-outlet name!="gsearch"></router-outlet> <=== rest routing should be here

routing.ts

{
        path: '',
        component: GSearchComponent,
        outlet: "gsearch"
 }
 {
        path: '',
        component: abcComponent,
        outlet: "abc"
 },
 {
        path: '',
        component: cdeComponent,
        outlet: "cde"
 }

2 个答案:

答案 0 :(得分:0)

您可以使用 Router Guard 的概念来允许路由。 例如: 在app-routing.module.ts中,这样调用 canActivate 属性

{
        path: '',
        component: GSearchComponent,
        canActivate: [AuthGuard],
        data: {name: 'gsearch'}
 }

Authguard 组件中实现您的查询,如

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(route: ActivatedRouteSnapshot, state: RouterStateSnapshot, protected router: Router) { }

    canActivate() {
        let name = route.data.name as string;
        if (name !== 'gsearch') {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}

确保在 app.module.ts

提供者中导入 AuthGuard

答案 1 :(得分:0)

app.component.html

<router-outlet name="gsearch"></router-outlet>
<router-outlet name="default"></router-outlet>

routing.ts

{
  path: '',
  component: GSearchComponent,
  outlet: "gsearch"
}
{
  path: '',
  component: abcComponent,
  outlet: "default"
}
{
  path: '',
  component: cdeComponent,
  outlet: "default"
}