当我的 angular 6 项目处于生产模式时,资产文件夹会移出 src。它在 webpack 配置中是这样设置的。
所以我对Angular是全新的。我想要一种干净的方式来根据NODE_ENV引用我的资产路径。我想这样做:
// Utility class
class Utilities {
public static getAssetsPath(env) {
return env == 'dev' ? 'src/assets' : '../assets';
}
private constructor() {}
}
// Component class
import {Utils} from 'shared/utilities/utils';
class MyComponent {
const ENVIRONMENT = process.env.NODE_ENV;
constructor(
private route: ActivatedRoute,
private router: Router
) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const eventUrl = /(?<=/).+/.exec(event.urlAfterRedirects);
const currentRoute = (eventUrl || []).join('');
this.myIcon =
Utils.getAssetPath(ENVIRONMENT) + '/icons/myIcon.png';
}
});
}
}
但我猜有一种更 Angular 的方法可以做到这一点,这样每个组件都可以访问它,而无需导入 Utilities 类。例如,像提供者一样。我的解决方案不是角度方式吗?感谢您的任何专业提示。
在组件中,您可以添加图像的位置,如下所示
<img src="../assets/icons/myIcon.png"/>
使用以下命令部署应用程序时应该不会有问题
ng build
解决此问题的一种方法是创建一个表示图像的组件,并将图像路径传递给该组件。在 html 中使用组件的选择器,如下所示:
<my-image-component [path]="'/icons/myIcon.png'"></my-image-component>
这样,只需在图像组件中注入实用程序类。