I was building a simple application where someone can search for a user by email in a form and then see the various pieces of data associated with that user.
For the top AppComponent component I have the followings routes:
@Routes([
{path: '/:name', component: CustomerComponent},
{path: '/search', component: SearchComponent}
])
The search path corresponds to the form to search for a customer and the /:name path is intended to be for displaying the data for that customer.
My idea was to have the Customer Component have some basic layout and perhaps things like a users profile picture and then have links to the different parts of a customer profile like so:
@Routes([
{path: '/profile', component: CustomerProfileComponent},
{path: '/loyalty', component: CustomerLoyaltyComponent},
{path: '/coupons', component: CustomerCouponsComponent},
{path: '/settings', component: CustomerSettingsComponent}
])
and html:
<div>
<span>
<a [routerLink]="['./profile']">Profile</a>
<a [routerLink]="['./loyalty']">Loyalty</a>
<a [routerLink]="['./coupons']">Coupons</a>
<a [routerLink]="['./settings']">Settings</a>
</span>
</div>
<div>
<router-outlet></router-outlet>
</div>
I was hoping this layout would let me have urls such as:
/search
/joe/profile
/joe/loyalty
/joe/coupons
/joe/coupons/14/
/joe/coupons/14/edit
...etc
The problem I am running into is that it seems within the child router I can't use the RouteSegment to get the users email. For example, within CustomerProfileComponent I implement OnActivate and try the following:
routerOnActivate(curr: RouteSegment) {
let name = curr.getParam('name');
console.log("profile says " + name);
}
However, this prints 'profile says undefined.' I suppose this is because :name route param doesn't belong directly to the CustomerComponent, rather it belongs to the Routes in the AppComponent.
I want to be able to be able to grab the name from the RouteSegment for each of these views and then be able to use that to hit some api to get specific data about that user.
I have read that one way to do it is to have a service that shares state data by having something like a 'current user' variable and inject the service it into all the components in the child routes.
However, I think it would make the application simpler if I didn't need to share state in this way across components.
Is there any way that I can get the name from the route or is there perhaps a better approach?
You need add the information in routeLink as follows
Where profile is property in the component
Also the URLs available will be
/profile/joe
orlayout/joe