我有一个字符细节组件,我想实现上一个和后一个按钮来切换字符。我已经实现了这样的事情:
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 :(得分:0)
您可以构建位置服务,该服务拥有“后退”API。
@Component({ directives: [ROUTER_DIRECTIVES] })
@RouteConfig([
{...},
])
class AppCmp {
constructor(private _location: Location) {
}
back() {
this._location.back();
}
}