Angular 4重载路由基于路径参数变化

时间:2017-08-14 13:42:12

标签: angular typescript

我已经看过几个例子,但我似乎无法获得params observable的订阅功能。我能够使router.events工作。我究竟做错了什么?

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]"

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

我有一个类似的用例,以下代码适用于我:

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,但这应该没有区别。