2017-03-08 53 views
2

我正在研究一個示例Angular 2應用程序,它也具有路由功能,下面是我的路由相關代碼。如何在根組件中標識頁面未找到路由[Angular 2]?

.... 
... 
RouterModule.forRoot([ 
     { path: '', component: LoginComponent },   
     { path: "spa/home", canActivate: [canActivateGuard], component: HomeComponent }, 
     { path: 'spa/about', canActivate: [canActivateGuard], component: AboutComponent }, 
     { path: 'spa/login', component: LoginComponent }, 
     { path: '**', component: PageNotFoundComponent} 
    ]) 
.... 
.... 

在我的根組件中,根據當前路由,需要將「blnDisplayMenu」的值設置爲true或false。 如果當前路由是「/ spa/login」,根組件中的下面的代碼將「blnDisplayMenu」設置爲false。

ngOnInit() { 

    this.router.events.subscribe(e => { 
     if (e instanceof NavigationEnd) { 
      if (e.url == '/' || e.url == '/spa/login') {     
       this.blnDisplayMenu = false; 
      } 
      else {      
       this.blnDisplayMenu = true; 
      } 
     } 
    }); 
} 

我的問題是如何設置「blnDisplayMenu」爲false即使當前路線是「**」。

回答

0

我想你可能需要添加更多的細節條件,當你想blnDisplayMenu真/假。根據有限的信息,這裏是我能想到的: 試着提出兩個條件。如果你想使你的blnDisplayMenu真正 2在哪裏,你想使你的blnDisplayMenu假 1))

我只是把樣品基於上面的代碼假設這兩條路線(水療/約和水療中心/家),你想讓blnDisplayMenu爲真。

由於「**」代表任何路線,所以如果您已經覆蓋了所有需要使blnDisplayMenu爲true的路線,那麼所有路線都將自動在else子句中進行覆蓋。

ngOnInit() { 
    this.router.events.subscribe(e => { 
     if (e instanceof NavigationEnd) { 
      if (e.url == '/spa/about' || e.url == '/spa/home') { // add any other route where you want blnDisplayMenu = true 
       this.blnDisplayMenu = true; 
      }else{ 
       this.blnDisplayMenu = false; 
      } 
     } 
    }); 
} 
0

隨着NavigationEnd,並從它的URL,你必須比較所有有效的URL,需要blnDisplayMenu值設置爲truefalse但比較所有路徑使用是不是好的辦法,所以你可以使用路由data選項組態。

設置一個標誌說displayMenu數據的路線**如下:

RouterModule.forRoot([ 
    { path: '', component: LoginComponent },   
    { path: "spa/home", canActivate: [canActivateGuard], component: HomeComponent }, 
    { path: 'spa/about', canActivate: [canActivateGuard], component: AboutComponent }, 
    { path: 'spa/login', component: LoginComponent }, 
    { path: '**', component: PageNotFoundComponent, data : { displayMenu: false } } 
]) 
...... 

然後使用ActivatedRoute在組件檢查displayMenu變量存在與否對你ActivatedRoute

@Component() 
export class OneComponent implements OnInit { 
    constructor(private route: ActivatedRoute) {} 

    ngOnInit() { 
    this.obs = this.route 
     .data 
     .subscribe(v => { 
     if(v.displayMenu === false) { 
      this.blnDisplayMenu = false; 
     } 
     }); 
    } 

    ngOnDestroy() { 
    this.obs.unsubscribe(); 
    } 
} 
+0

但如何設置爲「真」的其他路線? – refactor

+0

得到它,在其他 – refactor

+0

一個解決方案是使用'NavigationEnd'爲其他路線和'ActivatedRoute'爲'**'路線,但我不知道它的執行順序是否會影響輸出或不[可能會覆蓋'blnDisplayMenu'值],第二種解決方案是在所有其他路徑上將'displayMenu'設置爲'true',並在'ActivatedRoute''部分將'blnDisplayMenu'設置爲'true'。 – ranakrunal9