Akx*_*kxe 3 angular2-routing angular2-services angular
我想有一个服务,它有一个可观察的变量依赖于当前URL.
:programID -- program overivew
:programID/bug -- bug list
:programID/bug/:bugID -- bug overview
Run Code Online (Sandbox Code Playgroud)
哪里programID可以随时切换.我已经提供了一项服务,根据我从棱角分明的文档中的理解,我应该使用参数进行观察
ProgramService :(摘录)
currentProgramID: number
constructor(
private router: Router,
private route: ActivatedRoute,
private http: Http){
this.route.params.subscribe((params: Params) => {
console.log('Parent:', params['programID'])
})
this.route.children[0].params.subscribe((params: Params) => {
console.log('Childern:', params['programID'])
// Works if loaded while at url : 'abc123/bug/abc123'
})
this.route.params.subscribe((params: Params) => {
console.log('Hacky?:', this.route.snapshot.params['programID'])
})
}
Run Code Online (Sandbox Code Playgroud)
需要当前程序参考的组件:(提取)
program: Promise<program>
constructor(
private programService: ProgramService, ... ){}
ngOnInit() {
this.program = this.programService.getProgram(/*current program*/)
...
}
Run Code Online (Sandbox Code Playgroud)
但是我只获得了programID一次,并且当页面加载到正确的URL时.导航后我甚至都得不到.
之后我会切换到switchMap但为了测试目的,这更加到位.
您可以使用router.events和router.routerState.snapshot.root.firstChild阅读params:
@Injectable()
class ProgramService {
programId:string;
constructor(
private router: Router,
//private http: Http
){
this.router.events
.filter(e => e instanceof NavigationEnd)
.forEach(e =>{
var firstChild = router.currentRouterState.snapshot.root.firstChild;
console.log(firstChild.params);
console.log(firstChild.firstChild && firstChild.firstChild.firstChild && firstChild.firstChild.firstChild.params);
var newProgramId = firstChild.params['programID'];
if(this.programId != newProgramId) {
this.programId = newProgramId;
this.programService.getProgram(this.programId);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1979 次 |
| 最近记录: |