Angular 4: Routing to a route doesn't work
Solution 1
Turns out my firebase code is messed up - it tries to reload the page before going to another route. That caused an error, because some parameters that handed over from the previous route were missing.
export const routing = RouterModule.forRoot(APP_ROUTES, { enableTracing: true })
in app.routing.ts was very useful for debugging.
Solution 2
In your relative path this.router.navigate(['../collections']);
you are trying to navigate to localhost:4200/collections/collections
. Try this.router.navigate(['../']);
If this doesn't work, also supply the ActivatedRoute as a relativeTo parameter:
constructor(route: ActivatedRoute, router: Router) {}
navigate() {
this.router.navigate(['../'], { relativeTo: this.route });
}
relativeTo
works by creating a path relative to whatever entry you provide, and it does not necessarily need to be the current route.
Related videos on Youtube
user3255061
Updated on June 05, 2022Comments
-
user3255061 almost 2 years
There is some fundamental concept of routing in Angular 4 that I don't understand.
index.html:
<base href="/">
File structure:
- app |- app.routings.ts |- collections |-- collection.component.ts |-- collection.component.html |-- collectioninfo.component.ts |-- collectioninfo.component.html |- shared |-- header.component.html |-- header.component.ts
I have a link in my header.component.html:
<a class="nav-link" [routerLink]="['/collections']"> Collections </a>
If I click it I land on localhost:4200/collections. When a button is clicked, the url is programmatically changed (in collection.component.ts):
this.router.navigate(['/collections/', collection.name]);
I end up on localhost:4200/collections/name - all fine. Now I programatically want to get back to /collections (in collectioninfo.component.ts):
this.router.navigate(['/collections']);
But that doesn't work. The url doesn't change and I get an error that says a parameter couldn't be loaded - so apparently /collections/name is being loaded again. Thought it might is a path issue, but things like this also don't work:
this.router.navigate(['../collections']);
Additional info: When I manually reload the page while being on /collections I'm being forwarded to the home page again, but I think that is another issue and not related to this behaviour.
app.routing.ts:
const APP_ROUTES: Routes = [ ... { path: 'collections', component: CollectionComponent }, { path: 'collections/:id', component: CollectionInfo }, ];
-
user3255061 over 6 yearsThanks for the hint, unfortunately that doesn't work either (some behaviour).
-
user3255061 over 6 years@Surreal: It just works without the brackets anyway. But thanks for the hint.
-