2017-01-30 21 views
0

我有一個character-details組件,我想實現上一個和後一個按鈕來切換字符。我已經實現了這樣的事情:Angular:關於使用ActivatedRoute實現上一個和後退按鈕的問題

import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute, Router, Params } from '@angular/router'; 
import { CharacterService } from './character.service'; 
import { ICharacter } from './character'; 
import { Observable } from 'rxjs'; 
import 'rxjs/add/operator/switchMap'; 

@Component({ 
    moduleId: module.id.toString(), 
    templateUrl: "character-details.component.html", 
    styleUrls: ["character-details.component.css"] 
}) 
export class CharacterDetailsComponent implements OnInit { 

    character: ICharacter; 
    imageWidth: number = 150; 
    imageHeight: number = 300; 

    constructor(
     private _characterService: CharacterService, 
     private _route: ActivatedRoute, 
     private _router: Router 
    ) {} 

    ngOnInit(): void { 
     this._route.params 
      .switchMap((params: Params) => this._characterService.getCharacter(params['category'], +params['id'])) 
      .subscribe(
       (character: ICharacter) => this.character = character, 
       error => console.log(error) 
      ); 
    } 

    onBack(): void { 
     this._router.navigate(['../'], {relativeTo: this._route}); //, {category: this._route.snapshot.params['category']} 
    } 

    onNextCharacter(): void { 
     let category = this._route.snapshot.params['category']; 
     let id = +this._route.snapshot.params['id']; 
     this._characterService 
      .getNextCharacterId(category, id) 
      .subscribe(
       (id: number) => this._router.navigate(['../', id], {relativeTo: this._route}), 
       error => console.log(error) 
      ) 
    } 

    onPreviousCharacter(): void { 
     let category = this._route.snapshot.params['category']; 
     let id = +this._route.snapshot.params['id']; 
     this._characterService 
      .getPreviousCharacterId(category, id) 
      .subscribe(
       (id: number) => this._router.navigate(['../', id], {relativeTo: this._route}), 
       error => console.log(error) 
      ) 
    } 

} 

它工作正常,但這是正確的方法嗎?我沒有完全使用switchMap。我明白,因爲this._route.params是可觀察的,並且字符細節將被重用,所以我可以訂閱observable來獲取數據。但是如果我像下面那樣實現ngOnInit會怎樣?

ngOnInit(): void { 
     let category = this._route.snapshot.params['category']; 
     let id = +this._route.snapshot.params['id']; 

     this._characterService 
      .getCharacter(category, id) 
      .subscribe(
        (character: ICharacter) => this.character = character, 
        error => console.log(error) 
       ); 
    } 

即使組件將被重用,我可以使用this._route.snapshot嗎?我怎麼知道它實際上被重用?

謝謝你的時間!

回答

0

您可以構建定位服務,該服務擁有「返回」api。

@Component({ directives: [ROUTER_DIRECTIVES] }) 
@RouteConfig([ 
    {...}, 
]) 
class AppCmp { 
    constructor(private _location: Location) { 
    } 
    back() { 
     this._location.back(); 
    } 
}