Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can't I Inject RouterStateSnapshot into Login Component in Angular 2 App?

Simple Angular 2 question: why do I get a DI (dependency injection) error when I inject RouterStateSnapshot into my constructor in my Login Component? I'm trying to get the url prior to logging out, so I can pass that in for when a user logs back in (so it'll load their last visited component/page). This is proving more difficult than I expected. Even after importing it in and including RouterStateSnapshot in my constructor, I get a DI error. This is how I've set it up in my Login Component:

import { ActivatedRoute, ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';

constructor(private router: Router,
            private route: ActivatedRoute,
            private authenticationService: AuthenticationService,
            private alertService: AlertService,
            private state: RouterStateSnapshot,
            private authGuardService: AuthGuardService,
            private idle: Idle)
{

What's the problem here? What am I missing about RouterStateSnapshot that's different than ActivatedRoute, ActivatedRouteSnapshot, etc - which I can import in and inject without problem? Why can't I inject RouterStateSnapshot in the same way?

By the way, I can use RouterStateSnapshot in my authGuardService without issue. It's being used in my canActivate() function - and returns the right result. So what's different in this situation? Why can't I use it here in my Login Component?

like image 812
Muirik Avatar asked Nov 01 '17 21:11

Muirik


People also ask

What is Routerstatesnapshot in angular?

This is a tree of activated route snapshots. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. The following example shows how a component is initialized with information from the snapshot of the root node's state at the time of creation.

What is the difference between router and ActivatedRoute in angular?

Router does redirecting, don't call APIs about "getting the route information". If you needed to subscribe to changes in route, use this. router . ActivatedRoute does all "get the query params, get current URL, etc".

What is ActivatedRouteSnapshot in angular?

ActivatedRouteSnapshotlinkContains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.


1 Answers

I think you can get the RouterStateSnapshot from the RouterState. Consider this example:

constructor(private router: Router) {
    let routerStateSnapshot = this.router.routerState.snapshot;
}
like image 83
Robin Dijkhof Avatar answered Nov 06 '22 22:11

Robin Dijkhof