bir*_*win 19 angular2-routing angular
使用angular2,我想在我的组件中以编程方式打开辅助路径.
此代码打开带有"list"路径的路径,并在正确的命名路由器插座中打开路由,但我不确定如何将参数传递给路由:
this.router.navigate(['./', { outlets: { 'list-outlet': 'list' } }]);
Run Code Online (Sandbox Code Playgroud)
Mui*_*rik 27
显示特定产品详细信息的组件的路由需要该产品的路由参数ID.我们可以使用以下路由实现这一点:
export const routes: Routes = [
{ path: '', redirectTo: 'product-list', pathMatch: 'full' },
{ path: 'product-list', component: ProductList },
{ path: 'product-details/:id', component: ProductDetails }
];
Run Code Online (Sandbox Code Playgroud)
请注意:id路径的路径,该product-details路径将参数放在路径中.例如,要查看product-details带有ID5的产品页面,必须使用以下URL:localhost:3000/product-details/5
使用参数链接到路径
在ProductList组件中,您可以显示产品列表.每个产品都有一个链接到product-details路线,传递ID产品:
<a *ngFor="let product of products"
[routerLink]="['/product-details', product.id]">
{{ product.name }}
</a>
Run Code Online (Sandbox Code Playgroud)
请注意,该routerLink指令传递一个数组,该数组指定路径和路由参数.或者,我们可以通过编程方式导航到路线:
goToProductDetails(id) {
this.router.navigate(['/product-details', id]);
}
Run Code Online (Sandbox Code Playgroud)
在ProductDetails必须读取参数分量,然后加载基于所述产品ID在参数给出.ActivatedRoute服务提供了一个paramsObservable,我们可以订阅它来获取路由参数(参见Observables)
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'product-details',
template: `
<div>
Showing product details for product: {{id}}
</div>
`,
})
export class LoanDetailsPage implements OnInit, OnDestroy {
id: number;
private sub: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
// In a real app: dispatch action to load the details here.
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
paramsActivatedRoute 上的属性是Observable的原因是路由器在导航到同一组件时可能无法重新创建组件.在这种情况下,参数可能会更改,而不会重新创建组件.
来自这里的信息
bir*_*win 14
最后,我只需要使用一个数组来传递我的参数...见param1及param2以下.
this.router.navigate(['./', { outlets: { 'list-outlet': ['list', param1, param2]} }]);
Run Code Online (Sandbox Code Playgroud)
注意......我必须更改路由配置中的路径:
{
path: 'list/:param1/:param2',
component: ClaimListComponent,
outlet: 'list-outlet'
}
Run Code Online (Sandbox Code Playgroud)
然后在我的ngOnInit功能中,我可以像Muirik所说的那样将params从路由器中拉出来.
| 归档时间: |
|
| 查看次数: |
38395 次 |
| 最近记录: |