Angular 2 rc1中的RouteParams

mot*_*son 8 javascript angular2-routing angular

自beta以来我一直在尝试Angular 2,现在有了rc.0 +,有些东西已经改变了.

其中一个是RouteParams,无法从@ angular/router导入.当我尝试使用@ angular/router-deprecated时,我收到一条错误消息:

原始例外:没有RouteParams的提供商!

app.component:

@Routes([
  { path: '/', component: StartComponent },
  {path: '/:projId/:userName', component: ProjectListComponent},
  { path: '*', component: StartComponent },
])
Run Code Online (Sandbox Code Playgroud)

项目list.component:

import {Component, OnInit} from '@angular/core';
import {RouteParams} from '@angular/router-deprecated';

@Component({
  ...
})
export class ProjectListComponent implements OnInit {
  userName:string;
  projId:string;

  constructor(private params:RouteParams) {
    this.userName = params.get('userName');
    this.projId = params.get('projId');
  }
}
Run Code Online (Sandbox Code Playgroud)

从现在开始我可以在哪里导入RouteParams,或者是其他我做错了什么?

谢谢!

Gün*_*uer 10

一种方法是

  routerOnActivate(curr: RouteSegment) {
    this.userName = curr.getParam('userName');
    this.projId = curr.getParam('projId');
  }
Run Code Online (Sandbox Code Playgroud)


Sha*_*ala 7

你必须使用RouteSegment而不是RouteParams在angular2 RC 中使用.像这样 :-

import { Component } from '@angular/core';

import { Routes, RouteSegment, ROUTER_DIRECTIVES } from '@angular/router';

@Component({

  selector: 'about-item',

  template: `<h3>About Item Id: {{id}}</h3>`

})

class AboutItemComponent { 

  id: any;

  constructor(routeSegment: RouteSegment) {

    this.id = routeSegment.getParam('id');

  }
}

@Component({

    selector: 'app-about',

    template: `

      <h2>About</h2>
        <a [routerLink]="['/about/item', 1]">Item 1</a>
        <a [routerLink]="['/about/item', 2]">Item 2</a>
      <div class="inner-outlet">
        <router-outlet></router-outlet>
      </div>
    `,
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

  { path: '/item/:id', component: AboutItemComponent }

])

export class AboutComponent { }
Run Code Online (Sandbox Code Playgroud)