Angular 2 - ActivatedRoute不携带数据

时间:2017-01-10 09:49:16

标签: angular typescript

我按照角度网站上的教程,一切都很好。 但是,我尝试使用相同的模式创建另一个项目,但我无法通过ActivatedRoute传递数据。

以下是代码:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { LevelService } from './level.service';
import { RouterModule } from '@angular/router'

import { NgModule }      from '@angular/core';
import { LevelComponent } from './level.component';
import { SelectorComponent } from './selector.component';

@NgModule({
  imports:      [
    BrowserModule,
    RouterModule.forRoot([
      {
        path: '',
        redirectTo: '/selector',
        pathMatch: 'full'
      },
      {
        path: 'selector',
        component: SelectorComponent
      },
      {
        path: 'level/:id',
        component: LevelComponent
      }
    ])
  ],
  declarations: [ AppComponent, SelectorComponent, LevelComponent ],
  bootstrap:    [ AppComponent ],
  providers:    [ LevelService ],
})
export class AppModule { }

app.component.ts

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

@Component({
  moduleId: module.id,
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <router-outlet></router-outlet>
  `,
})
export class AppComponent {
  title = 'My App';
}

selector.component.ts

import { Component } from '@angular/core';
import { Level } from './level';
import { LevelComponent } from './level.component';
import { LevelService } from './level.service';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'my-selector',
  template:`
    <h3>Selector</h3>
    <a *ngFor="let level of levels"  (click)="gotoLevel(level)">
      <div>
        <h4>Level : {{level.id}}</h4>
      </div>
    </a>
  `
})

export class SelectorComponent implements OnInit {
  levels: Level[];

  constructor (private router: Router, private levelService: LevelService) {}

  getLevels(): void {
    this.levelService.getLevels().then(levels => this.levels = levels);
  }

  ngOnInit(): void {
    this.getLevels();
  }

  gotoLevel(level: Level): void {
    this.router.navigate(['/level', level.id]);
  }

}

level.service.ts

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

import { Level } from './level';
import { LEVELS } from './mock-levels';

@Injectable()
export class LevelService {
  getLevels(): Promise<Level[]> {
    return Promise.resolve(LEVELS);
  }

  getLevel(id: number): Promise<Level> {
    return this.getLevels().then(levels => levels.find(level => level.id === id));
  }
}

level.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { Level } from './level';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { LevelService } from './level.service';
import 'rxjs/add/operator/switchMap';

@Component({
  moduleId: module.id,
  selector: 'my-level',
  template: `
  <h3>Level {{level.id}}<h3>
  <button (click)="goBack()">Back</button>
  `
})

export class LevelComponent implements OnInit{
  @Input()
  level: Level;
  constructor (private levelService: LevelService, private route: ActivatedRoute, private location: Location){}
  ngOnInit():void {
    this.route.params.switchMap((params: Params) => this.levelService.getLevel(+params['id'])).subscribe(level => this.level = level);
  }
  goBack():void {
    this.location.back();
  }
}

level.ts

export class Level {
  id: number;
}

模拟levels.ts

import { Level } from './level';

export const LEVELS: Level[] = [
  {id: 1},
  {id: 2},
  {id: 3},
  {id: 4},
  {id: 5},
  {id: 6},
];

2 个答案:

答案 0 :(得分:1)

您的代码似乎很好,我能想到的唯一原因是更改检测可能没有开始。尝试更改这样的模板以确保在获得模板呈现的级别对象后:

@Component({
  moduleId: module.id,
  selector: 'my-level',
  template: `
  <div *ngIf="level">
    <h3>Level {{level?.id}}<h3>
    <button (click)="goBack()">Back</button>
  </div>
  `
})
export class LevelComponent implements OnInit{

答案 1 :(得分:0)

您可以像这样使用ActivatedRoute和Router。

import { Component, OnInit } from '@angular/core';
import { Router ,ActivatedRoute  } from '@angular/router';

@Component({
  selector: 'app-sub-cat',
  templateUrl: './sub-cat.component.html',
  styleUrls: ['./sub-cat.component.css']
})
export class SubCatComponent {
  public category={};
  constructor( private route:ActivatedRoute  ,private router:Router ){
  }
  onClickCategory(item){
    this.router.navigate(['shipping-details', {data: item.id}]);
    sessionStorage.setItem(item.id, JSON.stringify(item));
  }
  ngOnInit() {
    this.category =JSON.parse(sessionStorage.getItem(this.route.snapshot.params['data']));
  }

}