Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first route parameter in service

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.

like image 534
Akxe Avatar asked Feb 03 '17 01:02

Akxe


Video Answer


1 Answers

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

like image 183
Günter Zöchbauer Avatar answered Oct 03 '22 05:10

Günter Zöchbauer