【问题标题】:How do I set StyleUrls with variable in Angular 2如何在 Angular 2 中使用变量设置 StyleUrls
【发布时间】:2018-01-04 03:54:47
【问题描述】:

我有一个像这样的ts 文件

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]
})

但我得到了错误:

错误:找不到模块“。” 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:12webpackJsonpCallback http://localhost:4200/inline.bundle.js:26:23 http://localhost:4200/main.bundle.js:1:1 [WDS] 警告同时 编译。 vendor.bundle.js:13428:10 ./src/app/header/header.component.ts 32:17-45 关键依赖: 依赖项的请求是一个表达式 vendor.bundle.js:13493:4

我不知道怎么解决,谁能帮帮我

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

    这是因为你的变量 environment.profile 的值。

    请查看它是否指的是您的css的确切路径或将styleUrl的路径作为字符串。

    如果我误解了您的问题,请纠正我。

    ------------更新--------

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

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

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

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

    所以在我看来,这将是解决您的问题的一种更简洁的方法。

    【讨论】:

    • 它指的是我的css的确切路径
    • 你能试着用硬编码的字符串代替变量吗? (只是为了确认问题所在)
    • 它已导入,但我的示例代码中没有显示,我将更改它
    • 最后一件事,console.log(environment) 在构造函数调用中的输出是什么?
    • 在组件构造函数中为空,但在 ngOnInit Object { production: false, profile: "./test/test.css" } 中有值
    【解决方案2】:

    我正在解决同样的问题。

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

    关键依赖:依赖的请求是一个表达式 vendor.bundle.js:13493:4

    要修复它,您可以在 styleUrls 内的字符串中使用插值,如下所示。

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

    但请注意,我的调查在此变量被解释为通配符时停止,因此将所有文件映射到您的 main.js 内的变量的同一级别。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      相关资源
      最近更新 更多