2017-08-14 111 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) –