angular-cli:根据环境

时间:2017-04-05 11:16:30

标签: angularjs angular angular-cli

我使用 @ angular / cli:1.0.0 ,我想根据环境使用组件模板。我已经实现了这个:

import {Component} from '@angular/core';
import {environment} from '../environments/environment';

@Component({
  selector: 'tbe',
  templateUrl: environment.BASE_TEMPLATE_PATH+'app.component.html'
})
export class AppComponent {
  ...
}

我的环境设置如下:

export const environment = {
  production: false,
  BASE_TEMPLATE_PATH: '../templates/default/'
};

构建过程实际上有效,但浏览器控制台会抛出错误:

Error: Cannot find module "."

如果我用实际路径替换 environment.BASE_TEMPLATE_PATH +' app.component.html' ,它就会有效。

这里可以使用环境变量吗?如果是的话,我的错误在哪里?

更新

我为我的问题找到了更好的解决方案:http://www.smartjava.org/content/dynamic-component-loading-angular2-replace-compile

我已经更改了plunker示例来设置templateUrl而不是普通的html模板,这可行:https://plnkr.co/edit/tfxl3ba869oFtrqzyLNk

问题:

ComponentResolver已弃用,我无法将其与当前的Angular4版本一起使用。我尝试使用 ComponentFactoryResolver 但是它没有用。

2 个答案:

答案 0 :(得分:0)

之前我见过这个问题,它抱怨的原因是从environment.ts文件获取的路径相对于environment.ts文件而 {{1}如你所料。

尝试

AppComponent.ts

看看它是否有效。

为了获得更好的解决方案,您必须编写一个能够准确提供模板文件的绝对路径的函数。

这是一种非常丑陋的黑客行为方式,但似乎你明白了这里的风险。

答案 1 :(得分:0)

什么也会起作用(至少在最新的Angular版本中)

import {Component} from '@angular/core';
import {environment} from '../environments/environment';

const env = environment;

@Component({
  selector: 'tbe',
  templateUrl: env.BASE_TEMPLATE_PATH+'app.component.html'
})

export class AppComponent {
  ...
}

我正面临同样的任务,所以我在摆弄。我也可以确认,其他文件没有包含在你的AOT-build中。