2017-08-04 150 views
0

需要一些幫助,我只是想做一個簡單的任務:將app.component.ts中的變量傳遞給路由中的app.module.ts。將變量傳遞給路由配置

在app.component.ts我得到一些價值的服務,如:

ngOnInit(){ 
    this.subsc = this.someService.someMethod().subscribe(
     (someId: any[]) => { 
     console.log(someId); 
     }, 
     (error) => { 
     console.log("some error"); 
     } 
    ); 
    } 

我試圖讓這個someId並將它傳遞給像app.module.ts:

const pmRoutes: Routes = [ 
    { path: '', redirectTo: someId+'/some-other-component', pathMatch: 'full' }  
]; 

謝謝。

回答

0

這是不可能做你所描述的。在Angular中,您需要創建匹配給定模式的路線。如果你需要一個id,那麼這就是你的方法必須具備:

{ path: '', redirectTo: '{someId}/some-other-component', pathMatch: 'full' } 

然後你在組件處理的someId值。例如,假設您想在用戶單擊按鈕時導航到該路徑。然後,在(click)方法你必須:然後

constructor(protected router: Router) {} 

onClick(id) { 
    this.router.navigate([id, 'some-other-component']); 
} 

角度會看到,這條路線符合您所提供的一個,並加載相應的組件。

編輯

這是後衛應該怎麼樣子:

import { Injectable } from '@angular/core'; 
 
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router'; 
 
import { Observable } from "rxjs/Observable"; 
 
import { ServiceToFetchTheRouteValue } from 'somewhere'; 
 

 
@Injectable() export class RouteGuard implements CanActivate { 
 
    constructor(private service: ServiceToFetchTheRouteValue) { } 
 

 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any { 
 
     // assuming you get your value asynchronously and getValue() returns an Observable 
 
     return this.service.getValue().map((value: any) => { 
 
      // + is to convert the value to number; 
 
      return value === +route.params['someId']; 
 
     }); 
 
    } 
 
}

+0

謝謝您的回答。 但實際上這對我不起作用,因爲我想默認路由是這樣的:127.0.0.1/somevalue,這個值來自服務加載而不是點擊,這就是我想要做的。 –

+0

在這種情況下,您可能想要使用上面的解決方案以及一個將檢查'someId'值是否等於您的API提供的值的警衛。例如: '{path:'',redirectTo:'{someId}/some-other-component',pathMatch:'full',canActivate:CheckValueGuard}' –

+0

Yeap,我嘗試過canActivate,但我迷路了:(可以你給我舉個例子嗎? –