RouteParams in Angular 2 rc1

RouteParams in Angular 2 rc1

本文关键字:rc1 Angular in RouteParams      更新时间:2023-09-26

从测试版开始,我就一直在尝试Angular 2,现在有了rc.0+,有些事情发生了变化。

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

原始异常:没有RouteParams的提供程序!

app.component:

@Routes([
  { path: '/', component: StartComponent },
  {path: '/:projId/:userName', component: ProjectListComponent},
  { path: '*', component: StartComponent },
])

项目列表组件:

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');
  }
}

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

谢谢!

一种方法是

  routerOnActivate(curr: RouteSegment) {
    this.userName = curr.getParam('userName');
    this.projId = curr.getParam('projId');
  }

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

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 { }