2017-08-10 71 views
0

我一直是用來重定向從一個路由到另外一個很簡單的角度路由模塊:定義角路線根據路由參數重定向

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 

const routes: Routes = [ 
    { 
    path: 'foo', 
    redirectTo: 'bar', 
    pathMatch: 'full' 
    } 
]; 

@NgModule({ 
    imports: [RouterModule.forChild(routes)], 
    exports: [RouterModule], 
    providers: [] 
}) 
export class FooRoutingModule { } 

現在,我要換重定向使它取決於一個路由參數(可能會有比這個更多的參數)。所以,foo?para=0應該重定向到barA,而foo?para=1應該重定向到barB。達到此目的最簡單的方法是什麼?

回答

1

您可以使用Guards來操縱路由。

在你的情況下,CanActivate警衛應該很好地完成這項工作。在此處閱讀更多關於它們的信息:https://angular.io/guide/router#canactivate-requiring-authentication

@Injectable() 
export class MyGuard implements CanActivate { 

    constructor(public router: Router) {} 

    canActivate(route: ActivatedRouteSnapshot) { 
    switch(route.queryParams['para']) { 
    case '0' : 
     this.router.navigate(['my/url]); 
     break; 
    case '1': 
      .... 
    } 
    return false; 
    } 
} 

「return false;」在你的路由中非常重要,這樣當前的導航(在你的情況下爲'foo')被取消。

而在你的路由

const routes: Routes = [ 
    { 
    path: 'foo', canActivate:[ MyGuard ] 
    } 
]; 
+0

這是行不通的。在路由定義中,您需要組件或重定向。由於重定向無法保護,我需要引入一個空的假組件,這不是一個好的解決方案。 –

+0

請閱讀本文作者路易斯安那V3路由器V3關於組件路由更少的文章http://vsavkin.tumblr.com/post/146722301646/angular-router-empty-paths-componentless-routes –

+0

偉大的文章!我找到了解決方案,我會編輯你的答案。 –