2016-11-15 88 views
1

我有这样角2路由器链路与多个参数

path: 'projects/:id/settings' 

在我header.component.html的路线我想有一个链接到这个网页

<a routerLink="['projects', progectId,'settings']" routerLinkActive="active">cool link</a> 

我有一个project.component,当我点击某个项目时,我会进入项目页面。然后我需要有可能去projects/:id/settings或其他类似的路线。

如何从projects.component传递progectId变量?
或者,也许有人知道另一种方式来实现这一点。

回答

4

我有同样的问题对于这种route你应该使用routerLink这样的:

<a routerLink="/projects/{{progectId}}/settings" routerLinkActive="active">cool link</a> 

,改变你的route pathrouting module这样的:

{ path: ':id/settings', component: YourComponent} 

额外的信息来获得projectId您应该按照下列步骤操作:

  1. 在您的component constructor中注射ActivatedRouteobject
  2. 在您的component中定义一个名为projectIdvariable
  3. 获取params通过activatedRouteobjectngOnInit()方法。
  4. 最后,你应该getprojectIdhtml这样的:{{projectId}}

    import {Router, ActivatedRoute, Params} from '@angular/router'; 
    
    @Component({ 
        selector: 'app-your-component', 
        templateUrl: './your-component.component.html', 
        styleUrls: ['./your-component.component.css'] 
    }) 
    
    export class YourComponent implements OnInit { 
    
        private projectId: string; 
    
        constructor(private activatedRoute: ActivatedRoute) {} 
    
        ngOnInit() { 
        this.activatedRoute.params.subscribe((params: Params) => { 
        this.projectId = params['id']; 
        }); 
    }} 
    
0

我一般这样做的组件类这样

somefunctionName() { 
    let link = ['/summary', this.param1, this.param2]; 
    this.router.navigate(link); 
} 

然后调用从HTML代码这样

<a (click)="somefunctionName()"> 

在你的情况的功能,因为我假设你是通过循环你的项目,你可以用这样的参数调用你的函数

<a (click)="somefunctionName(pass the parameter here)"> 

然后改变函数定义来反映这一点。

+0

对不起,但也许哟不了解我。我知道如何建立一个链接。我问我怎么能从另一个组件获得一个:id参数?因为我只在project.component中拥有它,但是想要在header.component中拥有它。 –

+0

对不起,我误解了你的问题。我们可以请你看看你是如何调用你的HTML中的其他组件?根据这段代码,这将是一个简单的输入变量或视图子代的情况。 – TyAnthoney

+0

我解决了这个问题,通过创建一个服务来保存当前的项目,然后可以在任何地方使用它 –