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內。

如果我能解決通配符問題,我會更新我的答案!