Home > other >  Angular 14 serve from different folder, cannot match any route
Angular 14 serve from different folder, cannot match any route

Time:09-01

I am serving my angular application at path domain.com/app1/

I want the browser to show url as following: domain.com/app1/page1 or domain.com/app1/page2

My angular.json has "baseHref": "/app1/" and App module has { provide: APP_BASE_HREF, useValue: '.' }

and App routing has

[
  {
    path: 'app1',
    redirectTo: 'page1',
    pathMatch: 'full'
  },
  {
    path: 'page1',
    component: OneComponent
  },
  {
    path: 'page2',
    component: TwoComponent
  }
]

It is working perfectly if i visit the domain.com/app1, angular will redirect to domain.com/app1/page1

However if i reload or try to visit domain.com/app1/page1 directly then i am getting Cannot match any routes. URL Segment: 'app1/page1'

I cannot find anything in documentation. Can anyone help?

CodePudding user response:

page1 and page2 needs to be children of app1, like this:

            [
          {
            path: 'app1',
            pathMatch: 'full',
            children: [
             {
            path: 'page1',
            component: OneComponent
          },
          {
            path: 'page2',
            component: TwoComponent
          },
          {
            path: '', 
            redirectTo: 'page1'
          }
        ]
          },
        ]

CodePudding user response:

Try this way:

[
  {
    path: '',
    redirectTo: 'page1',
    pathMatch: 'full'
  },
  {
    path: 'page1',
    component: OneComponent
  },
  {
    path: 'page2',
    component: TwoComponent
  }
]

And in your index.html <base href="/app1">. Just with this should work.

In the other hand, if you want to use the DI APP_BASE_HREF apprach you could put this in your AppModule:

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/app1'}]
})
class AppModule {}
  • Related