Created
September 12, 2020 10:06
-
-
Save dmorosinotto/cb1b59c2ad3c58dfb29bb92bb0e9260a to your computer and use it in GitHub Desktop.
Angular Service to get/inject current ActivatedRoute + Params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from "@angular/core"; | |
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router"; | |
import {Observable} from "rxjs"; | |
import {first, filter, map, switchMap} from "rxjs/operators"; | |
@Injectable({providedIn: 'root'}) | |
export class CurrRouteService { | |
constructor( | |
private route: ActivatedRoute, | |
private router: Router | |
){} | |
public getActivatedRouteParameter(): Observable<any> | |
{ // CODE BY @anduser96 Andrei Gatej READ INFO: https://stackoverflow.com/questions/63854458/angular-report-current-route-and-params-to-any-component/63858102#63858102 | |
let params | |
params = this.router.events.pipe( | |
filter(e => e instanceof NavigationEnd), | |
map((): ActivatedRoute => { | |
let route = this.route; | |
while (route.firstChild) { | |
route = route.firstChild; | |
} | |
return route; | |
}), | |
filter((route: ActivatedRoute) => route.outlet === 'primary'), | |
switchMap((route: ActivatedRoute) => route.paramMap.pipe(first())) | |
//FIRST NEEDED TO AVOID PROBLEM WITH ROUTE REUSE -> NEW VALU EMITTED SEE: https://github.com/angular/angular/blob/6768fe9927ad4b9b81c5f8094c42c771d1047f56/packages/router/src/router_state.ts#L422-L448 | |
tap(console.log) //MORE INFO ON CREATION OF ActivatedRoute -> SOURCE: https://github.com/angular/angular/blob/6768fe9927ad4b9b81c5f8094c42c771d1047f56/packages/router/src/create_router_state.ts#L76-L80 | |
); | |
return params; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment