Reputation: 1237
So I have my fully functional static router within my awesome angularjs-powered single page application and now I get the task to make certain routes dynamic.
Say until now I had the following parametric paths:
^/user/:userName
^/product/:productName
^/category/:categoryName
Now they would all need to respond to the path ^/:slug
, which would make a call to some backend API to get the type of resource that corresponds to that slug and finally forward the request to a specific controller
with its specific resolve
, templateUrl
, abstract
and data
.
Any thoughts?
(EDIT: I guess the same functionality would be possible with route mirrors (aka transparent forwards) where internally another route than the requested is triggered, even though the route change is not publicly visible. But I'm still ignorant towards whether any of this is possible in angular or ui-router... )
Upvotes: 4
Views: 3153
Reputation: 1237
I figured it out. It ain't pretty but it works nicely.
Besides renaming my existing routes above to ^/:username
(alias 'profile'), ^/:productName
(alias 'products') and ^/:categoryName
(alias 'category'), I created a new generic route /:slug
with its controller ResolverController
. The latter must be declared first in the $stateProvider
.
ResolverController
is the following function:
function ($state, $stateParams, resource) {
switch (resource) {
case 'user':
$state.go('profile', {'username': $stateParams.slug});
break;
case 'product':
$state.go('products', {'productName': $stateParams.slug});
break;
case 'category':
$state.go('category', {'categoryName': $stateParams.slug});
break;
default:
// 404
break;
}
}
You might wonder about the third parameter resource
. It's returned by the resolve of this state and holds the information about the type of the resource of the requested slug.
Upvotes: 3