Angular fails to fetch CSS file on navigation to nested route

Viewed 1022

When directly navigating to a child component in prod mode (ng serve --prod) it fails to load the CSS file, trying to fetch it from a nested path. For instance, navigating to "localhost:4200/doc/" the CSS Request URL is:

localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css.

The error that is given:

Refused to apply style from 'http://localhost:4200/doc/styles.6eab038f040a1c7c7ed6.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

When accessing the root (localhost:4200) the CSS is loaded correctly. If you then navigate to the child component through the app itself, the problem does not occur.

It only occurs in prod mode, not on the development server. Changed nothing to the regular settings regarding styles.css, it is situated in the default folder.

          "styles": [
          "src/styles.css"
        ],

Anyone has any idea how this problem could be caused?

Edit

Found out that the problem lies in navigating to nested routes (helped by the reply of mikegross).

On a route without a nested parameter the problem does not occur, but on a route with a nested parameter (for instance 'doc/:id') it does.

Router module:

const routes: Routes = [
  { path: '', redirectTo: 'list', pathMatch: "full"},
  { path: 'list', component: ListComponent},
  { path: 'doc/:id', component: DocumentComponent},
  { path: '**', redirectTo: ''},
];

@NgModule({ 
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Update (feb. 28)

Since it was still a small project I generated a new angular project, installed same dependencies and literally copy pasted the code.

Although I have no idea why, in the new project the problem does not occur. The only difference lies in a minor version bump (ng 9.0 to 9.1).

2 Answers

I know this is an older post, but I got around this by using query parameters instead of route parameters. example:

const routes: Routes = [
  { path: '', redirectTo: 'list', pathMatch: "full"},
  { path: 'list', component: ListComponent},
  { path: 'doc', component: DocumentComponent},
  { path: '**', redirectTo: ''},
];

(I removed the :id from "doc/:id")

Navigate to the route:

route this._router.navigate(['/doc'],{queryParams: {id: id}});

Then retrieve the query parameter:

this._activatedRoute.snapshot.queryParamMap.get('id');

Coming late to the party. I had the same error with React in 2022.

Initially, I declared the CSS file with a relative path, as follows:

<link rel="preload" href="./style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>

After changing it to an absolute path, it worked

<link rel="preload" href="/style/Avenir-Light.woff2" as="font" type="font/woff2" crossorigin>

Hope it helps future readers.

Related