2017-08-04 126 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,但我迷路了:(可以你给我举个例子吗? –