问题
I am having troubles (all sorts of errors in very unexpected places) and my best guess is that it happens because of the way routing is set up.
This is my app-routing.module.ts
const appRoutes: Routes = [
{ path: 'calendar', component: CalendarComponent, canActivate: [AuthGuard] },
{ path: 'calendar/:urlString', component: CalendarComponent, canActivate: [AuthGuard] },
{ path: 'myprofile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'profiles', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'locations', component: LocationComponent, canActivate: [AuthGuard] },
{ path: 'login', component: AuthComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
];
@NgModule({
imports: [ RouterModule.forRoot(appRoutes) ],
exports: [ RouterModule ]
})
Then, in CalendarComponent.ts I have this piece of code:
imports (...)
constructor(
private activatedRoute: ActivatedRoute,
){
}
public ngOnInit(): void {
this.activatedRoute.params.subscribe((params: Params) => {
this.resolveURLParams(params);
});
}
public resolveURLParams( params ): void {
// do stuff based on params
}
Anyway, just a half year ago (some RC @Angular2) I could start the app by typing any of these directly into the browser
localhost:3000
,
localhost:3000/calendar
or
localhost:3000/calendar/2017-05-27
and would get expected results. Now I have to start from localhost:3000
, so that the app routes me through ../login
--> ../calendar
--> ../calendar/2017-05-27
, otherwise I get all sorts of troubles, like Cannot read property subscribe of null
or Cannot activate already activated outlet
.
I guess, the routing has been updated and I am lagging behind. Any help on this, please?
回答1:
There might be a time delay in subscribing to the route params, I suggest you to use non-Observable option using the service ActivatedRouteSnapshot
Inject the service ActivatedRouteSnapshot
and get the params using
this.activatedRoute.route.snapshot.params.urlString
Note: use pathMatch:full
for the definition
{ path: 'calendar', component: CalendarComponent, canActivate: [AuthGuard] , pathMatch:'full'},
as your route will fall through in the order of definition and tries to match the param one with the above
回答2:
This is actually a bummer, but there was no problem with the way routes and ActivatedRoute subscription worked. The problem was with the AuthGuard I was using, which was broken. Now that I've fixed the guard, all the problems went away. So, thanks for trying to help.
来源:https://stackoverflow.com/questions/44221485/angular2-routing-with-parameters-fails