I would like to have a service, that have an observable with a variable dependant of current URL.
:programID -- program overivew
:programID/bug -- bug list
:programID/bug/:bugID -- bug overview
Where programID
may switch at any point. I have made a service, that from what I understood from angular docs, should make an observable with parameters
ProgramService: (extract)
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'])
})
}
Components, that need current program reference: (extract)
program: Promise<program>
constructor(
private programService: ProgramService, ... ){}
ngOnInit() {
this.program = this.programService.getProgram(/*current program*/)
...
}
However I only get the programID
once, and that when the page is loaded at correct URL. I don't even get if after navigating.
Afterwards I will switch to switchMap
but for testing purposes, this was more in place.
You can use router.events
and router.routerState.snapshot.root.firstChild
to read the 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);
}
});
Plunker example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With