2017-08-14 10 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)); 
    }); 

    } 
} 

これはこれは、リンクがテンプレート内のセットアップ

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

this.activatedRoute.params.subscribeでエラーが発生しますか? – LLai

+0

エラーなし、正しいURLでNavigationStart、RoutesRecognized、およびNavigationEndのみ。 – Grim

+0

hmm、あなたのcomponent.tsコードをもう少し投稿できますか? (コンストラクタ、activatedRouteインポートなど)コンストラクタまたはngOnInitライフサイクルフックを購読していますか? – LLai

答えて

0

あるかであるルート(子)

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

である私は、同様のユースケースを持っているし、次のコードは、のために働きます私:

export class ProductDetailComponent { 

    productID: string; 

    constructor(private route: ActivatedRoute) { 

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

親コンポNENTは、私は製品のリストを持っているし、次のように選択した製品のIDを渡します

constructor(private _router: Router){} 

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

私はrouterLinkを使用していないが、これは何の違いを作るべきではありません。

2

議論の中で、問題は、間違ったコンポーネントの中から以下のコードを使用しようとしていたという事実に沸きました。

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

新しいバージョンのAngularルータは、 'params'ではなく' paramMap'を介してルータのパラメータにアクセスすることを提案しています。 [Docs](https://angular.io/guide/router#activated-route-in-action) –

関連する問題