2017-07-28 56 views
0

设置StyleUrls可变我有一个ts文件中像这样如何在角2

export const environment = { 
    production: false, 
    profile : './test/test.css' 
}; 

我想进口environment.profile,并设置它,这样我可以在StyleUrls使用它像

import { Component, OnInit } from '@angular/core'; 
import { TranslateService } from "@ngx-translate/core"; 
import {environment} from "../../environments/environment"; 

@Component({ 
    selector: 'app-header', 
    templateUrl: './header.component.html', 
    styleUrls: [environment.profile] 
}) 

但我得到的错误:

Error: Cannot find module "." main.bundle.js:250:62 webpackMissingModule http://localhost:4200/main.bundle.js:250:62 ../../../../../src/app/header/header.component.ts http://localhost:4200/main.bundle.js:250:29 webpack_require http://localhost:4200/inline.bundle.js:55:12 ../../../../../src/app/app.module.ts http://localhost:4200/main.bundle.js:71:83 webpack_require http://localhost:4200/inline.bundle.js:55:12 ../../../../../src/main.ts http://localhost:4200/main.bundle.js:291:74 webpack_require http://localhost:4200/inline.bundle.js:55:12 [2] http://localhost:4200/main.bundle.js:309:18 webpack_require http://localhost:4200/inline.bundle.js:55:12 webpackJsonpCallback http://localhost:4200/inline.bundle.js:26:23 http://localhost:4200/main.bundle.js:1:1 [WDS] Warnings while compiling. vendor.bundle.js:13428:10 ./src/app/header/header.component.ts 32:17-45 Critical dependency: the request of a dependency is an expression vendor.bundle.js:13493:4

我不知道如何解决它可以someo ne帮我

回答

0

它是因为你的变量值environment.profile

请参阅是否指向您的css的确切路径将styleUrl的路径作为字符串提供。

如果我错误地解释了你的问题,请纠正我。

--------------------- UPDATE --------------------

根据评论中的讨论,我只是建议使用基于类而不是Const的方法。

因为Const在组件的构造函数中调用时不返回任何东西,并且在ngOnInit()中返回正确的值。

https://www.youtube.com/watch?v=uq4kLWPfosU

这里是视频链接到角的新波士顿的教程,我提到。在那里,他使用了一个名为Config类各种细节存储诸如MAIN_HEADING等。

所以根据我来说,那将是解决你的问题更清洁的方式。

+0

它指的是我的css的确切路径 – user2843943

+0

你可以尝试把一个硬编码的字符串,而不是变量? (只是为了确认问题是什么) –

+0

工作正常 – user2843943

0

我正在解决同样的问题。

基本上,你不能直接在你的styleUrls中使用表达式,这是这个日志告诉你的。

Critical dependency: the request of a dependency is an expression vendor.bundle.js:13493:4

要修复它,你可以在styleUrls中的字符串中使用插值,就像这样。

@Component { 
    …… 
    styleUrls: `${environment.profile}` 
} 

要小心的是,我的调查停止在该变量被解释为一个通配符,因此映射在variabl同级别的所有文件的main.js内。

如果我能解决通配符问题,我会更新我的答案!