1

Normally I use this kind of routing to load my components in app-routing.module.ts

const routes: Routes = [
{
path: '', component: HomeComponent
},
{
path: 'product-list', component: ProductListComponent
},
{
path: 'product', component: ProductComponent
}
];

But, I would like to base the routing on a http call to determine what component to load

For a example, I want to be able to have these URL's:

/nike

/nike-airmax

The first URL should load a product list page, and the second a product page

I have a http call to get the page type, it looks like this:

this.http.get(domain + 'api/ApiRoute?url=' + this.activatedRoute

(returns a int value, but it can return whatever I need)

Problem 1

I don't know how to call a service (that returns the type) from app-routing-module.ts

Problem 2

I don't know how to use the "type" from the service to determine the routing

1 Answer 1

2

It is impossible to do with Angular built in routing as its configuration should be static. the best thing you can do is create your own SwitchComponent on a path: ':productName', where you will be able to render one of your required components with *ngIfs.

 ngOnInit(){
   this.activatedRoute.params.pipe(
     switchMap((params) => this.myService.getComponentType(params['productName']))
   ).subscribe(type => this.componentType = type);
 }

.....
<product *ngIf="componentType == 'product'"></product>
<product-list *ngIf="componentType == 'product-list'"></product-list>
Sign up to request clarification or add additional context in comments.

5 Comments

You are correct it's difficult to do with angular because of the static nature of routing, but I believe it is possible. One way to achieve it could be to have a lazy route that actually retrieves an entire NG module from a static url that actually serve different modules based on server-side logic. Admittedly, this would be rather awkward and probably not worth the trouble.
even if you interfere into angular bundling and setup correct hashing logic on the backend you won't be able to navigate between paths. in case you've already downloaded ProductModule on a path /backendGeneratedModule you will no longer be able to open ProductListModule because angular will think the path is already "cached"
Indeed, I didn't think of that, You're absolutely right.
Thank you @AluanHaddad, I hoped I wouldn't have to go that way, but it works :)
@Marcus did you mean to address your comment to @Andrei?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.