我正在开发一个 Angular 6.x
应用程序,我正在尝试(动态)更改主题。
CLI
正确编译所有内容,但在开发人员控制台
中我收到此错误消息。
Refused to apply style from 'http://localhost:4200/vendor/theme-light.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
我的文件结构是这样的,路径是正确的
project
|-src
|-vendor
|-theme-light.css
|theme-dark.css
我的主题更改代码看起来是这样的
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
@Component({
..
..
})
linkRef: HTMLLinkElement;
themes = [
{ name: 'Light', href: '../vendor/theme-light.css' },
{ name: 'Dark', href: '../vendor/theme-dark.css' }
];
constructor(@Inject(DOCUMENT) private document: Document, @Inject(PLATFORM_ID) private platformId: Object) {
if (isPlatformBrowser(this.platformId)) {
let theme = this.themes[0];
try {
const stored = localStorage.getItem('theme');
if (stored) {
theme = JSON.parse(stored);
}
} catch (e) {
}
this.linkRef = this.document.createElement('link');
this.linkRef.rel = 'stylesheet';
this.linkRef.href = theme.href;
this.document.querySelector('head').appendChild(this.linkRef);
}
}
setTheme(theme) {
localStorage.setItem('theme', JSON.stringify(theme));
this.linkRef.href = theme.href;
}
现在,我真的不明白为什么会这样。我错过了什么吗?如果需要,请随时询问更多详细信息。
任何帮助将不胜感激。
谢谢
最佳答案
看起来 href 是错误的。
有个好answer与您完全一样的不同问题:
此错误消息的常见原因是,当浏览器尝试加载该资源时,服务器会返回一个 HTML 页面,例如,如果您的路由器捕捉到未知路径并显示没有 404 错误的默认页面。当然,这意味着该路径不会返回预期的 CSS 文件/图像/图标/任何...
解决方案是找到正确的路径和路由器配置,以便在访问该路径时获得纯 CSS 文件/图像等。
在您的情况下,它是 css href。
关于html - 由于 MIME 类型 Angular 应用程序未加载样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553134/