【问题标题】:How use variable in the path while import typescript导入打字稿时如何在路径中使用变量
【发布时间】:2017-09-14 01:59:50
【问题描述】:

是否可以将变量(或常量)放入路径,而不是将整个路径写为字符串文字。看起来,Angular 只接受字符串文字。

import aClass = require("./simpleClass"); 
import { aComponent } from aClass.myClass.Root + 'tutorial.component';

我的班级:

export class myClass{    
    public static Root = "./"
}

在此示例中,aClass.myClass.Root + 'tutorial.component' 有错误,已解释

【问题讨论】:

  • “有错误说明”什么错误?
  • 编译器说路径应该是字符串
  • aClass.myClass.Rootundefined... 而是使用aClass.Root?虽然我仍然认为这行不通。

标签: javascript angular typescript


【解决方案1】:

它现在确实支持动态导入..

就这样吧

async () => {
  const { aComponent } = await import(aClass.myClass.Root + 'tutorial.component');
}

更多信息

http://2ality.com/2017/01/import-operator.html

试试这个

import aClass from "./simpleClass"; 
var aComponent = require(aClass.myClass.Root + 'tutorial.component').aComponent;

import { myClass } from './simpleClass';
const { aComponent } = require(myClass.Root + 'tutorial.component');

【讨论】:

  • 它有效,谢谢! @siamak-ferdos 这应该是一个公认的答案
  • 在 Angular 中效果很好! import { env } from 'environments'; export function getsomejson(){ return 'assets/path/' + env.some_var + '/file.json' } 然后在 component.ts 你只需要:import {getsomejson} from 'path'; ... style = getsomejson();,然后在 html 你只需要:[style]="style | async"
猜你喜欢
  • 2022-11-05
  • 1970-01-01
  • 2017-03-14
  • 2021-05-03
  • 2017-07-21
  • 2021-01-20
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多