Reputation: 1359
Params subscribe in targetComponent:
import Router from @angular/Router
export class TargetComponent {
constructor(private activeRoute: ActivatedRoute) {
this.activeRoute.params.subscribe(params => {
console.log(params) // receives targetName but with different attributes
console.log(params.name); // sometimes params has attribute name
console.log(params.target); // and sometimes target
});
}
}
Sending params from firstComponent
import ActivatedRoute from @angular/Router
this.router.navigate(['/', 'search' , targetName]);
Sending params form secondcomponent
this.router.navigate(['/', 'table', targetName]);
Route Configuration
const routes: Routes = [
{
path: '',
redirectTo: 'welcome',
pathMatch: 'full'
},
{
path: 'search/:name',
component: SearchItemComponent
},
{
path: 'table/:target',
component: TableDataComponent
}
]
Trying to understand why the params object would have 'target' attribute and sometimes 'name' to store value when navigated from different components.
Upvotes: 0
Views: 827
Reputation: 395
I assume you're using something along the lines of Angular's RouterModule?
One thing I could think of is that some of the code in there is duplicated and some routes have a roundabout way of getting to their destination.
For example, you may see code looking something like this:
const routes: Routes = [
{ path: 'target/:name', component: TargetComponent, canActivate: [AuthGuard]},
{ path: 'target/:target', component: TargetComponent}
]
The values behind the ':' are the deciding factor of what the activated routes' parameters' name are going to be (in this case either 'name' or 'target'). So, if you'd try to access target/name, but canActivate
returns false, it goes over to target/target. Virtually, nothing changed, but the parameters' name is obviously going to be different, though the value won't be (specifically, you'd be able to access params.target
, but not params.name
).
Additional Hint
One thing to note is that the Router literally goes from top to bottom. So, given a similar scenario, if you'd switch the Array to look like this:
const routes: Routes = [
{ path: 'target/:target', component: TargetComponent},
{ path: 'target/:name', component: TargetComponent, canActivate: [AuthGuard]}
]
The ActivatedRoutes' parameters' name would always be 'target', since there is no canActivate-Guard that could ever stop the Router from accessing that Route
Upvotes: 1