2017-08-14 110 views
0

我已经看过几个例子,但我似乎无法获得params可观察工作的订阅功能。我能够使router.events工作。我究竟做错了什么?基于路径参数变化的角度4重载路由

import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute, Router } from "@angular/router"; 
import { ProjectService } from '../../services/project.service'; 
import { Project } from "../../domain/project"; 


@Component({ 
    selector: 'app-nav-bar', 
    templateUrl: './nav-bar.component.html' 
}) 
export class NavBarComponent implements OnInit { 

    projects: Project[] = []; 


    constructor(private projectService: ProjectService, 
       private route : ActivatedRoute, 
       private router : Router) { 

    this.projectService.getProjects(); 
    } 

    ngOnInit() { 

    this.projectService.projectsChange.subscribe(result => { 
     this.projects = result; 
    }); 

    this.projectService.projectChange.subscribe(result => { 
     this.projectService.getProjects(); 
    }); 

    // This only works the first time the component is routed to 
    this.activatedRoute.params.subscribe(params => { 
     console.log(params); 
     console.log("did this work at all?"); 
     this.projectService.getProject(params['id']); 
    }); 

    // This works when the param changes in the router 
    this.router.events.subscribe((val) => { 
     console.log(this.router.url); 
     let url = this.router.url; 
     let id = url.substring(url.length - 2, url.length); 
     this.projectService.getProject(Number(id)); 
    }); 

    } 
} 

这是路线(孩子)

{ path: '', component: DashboardComponent, canActivate: [AuthenticationGuard], 
    children: [ 
     { path: 'projects/:id', component: ProjectComponent } 
    ] 
    } 

这是链接如何模板

[routerLink]="['/projects/', project.id]" 
+0

您是否在使用this.activatedRoute.params.subscribe时遇到错误? – LLai

+0

没有错误,只是NavigationStart,RoutesRecognized和NavigationEnd与正确的网址。 – Grim

+0

嗯,你可以发布一些更多的component.ts代码吗? (构造函数,activatedRoute导入等)您是否在构造函数或ngOnInit生命周期钩子中订阅? – LLai

回答

0

我也有类似的用例中设置和下面的代码适用于me:

export class ProductDetailComponent { 

    productID: string; 

    constructor(private route: ActivatedRoute) { 

    this.route.paramMap 
     .subscribe(
     params => this.productID = params.get('id')); 
    } 
} 

在母公司新界东北我的产品列表,并通过所选择的产品ID如下:

constructor(private _router: Router){} 

    onSelect(prod: Product): void { 
    this.selectedProduct = prod; 
    this._router.navigate(["/productDetail", prod.id]); 
    } 

我不使用routerLink,但是这应该没有什么区别。

2

Thnx to LLai在讨论中,问题归结为我试图从错误的组件内使用下面的代码。

this.activatedRoute.params.subscribe(params => { 
    console.log(params); 
    console.log("did this work at all?"); 
    this.projectService.getProject(params['id']); 
}); 
+2

较新版本的Angular路由器建议通过'paramMap'而不是'params'访问路由器参数。 [文件](https://angular.io/guide/router#activated-route-in-action) –