Search code examples
angularangular-routingangular-routerangular-activatedroute

Actived Route is undefined in service's constructor


There is a service trackUrlService which is imported to CoreModule

export class TrackUrlService implements OnDestroy {

    ...

    constructor(private router: Router, private route: ActivatedRoute) {
        ...

        this.subs.add(
            this.route.params.subscribe((params: Params) => {
                console.log(params.workflowId); // output: undefined
                ...
            })
        );
    }
...

There is a component DummyComponent

ngOnInit() {
        this.subs.add(
            this.trackUrl.currWorkflowId.subscribe(currWorkflowId => {
                console.log(currWorkflowId); // output: undefined
            }),
            ...
            /* this.route.params.subscribe(params => {
                console.log(params.workflowId) // output: 391 (correct)
            }), */
         ...

QUESTION:

Why calling this.route.params from service's constructor outputs undefined?

But calling this.route.params from the components' ngOnInit() works and outputs a correct value.


Solution

  • From ActivatedRoute docs: "Provides access to information about a route associated with a component that is loaded in an outlet", i.e ActivatedRoute params visible just inside route component.