Angular 5 - 在 ngOnInit 中循环获取数据

Angular 5 - Looping in the ngOnInit for data

我有这个数据:

myData = [
 {
    "name": "namehere"
    "path": "somepath",
    "const": "someconst",
    "method": "somemethod"
    ""
  },
  {
    "name": "othernamehere"
    "path": "othersomepath",
    "const": "othersomeconst",
    "method": "othersomemethod"
    ""
  }
];

我要做的是在 ngOnInit 上创建一个循环,这样我就可以动态地进行多次导入。

从数据中提取的 myData.path 等看起来像这样

ngOnInit() {

    import(myData.path).then(module => {
      const myData.const = new module.myData.name().myData.method();
    });

  }

你可以试试forEach函数:

myData.forEach((data,index) => {
    import(data.path).then(module => {
        this.myData[index].const = new module.data.name().data.method();
    });
})

建议您尝试与 @vivek 建议的解决方案相同,但使用最新 ES 版本的方法:

for(const [index, data] of Object.entries(myData)) {
  const module = await import(data.path);
  myData[index].const = new module.data.name().data.method();
});

这里我用for...of用它的回调代替foreach,用await代替promise级别的缩进。

函数前面需要异步:

async ngOnInit() {

管理其中await的使用

我们可以按需异步导入和加载模块

myData = [
 {
    "name": "namehere"
    "path": "somepath",
    "const": "someconst",
    "method": "somemethod"
    ""
  },
  {
    "name": "othernamehere"
    "path": "othersomepath",
    "const": "othersomeconst",
    "method": "othersomemethod"
    ""
  }
];

myData.map((module)=>{
   import(module.path+'/'+module.name).then(module => {
      // Here you should use an array and assign each module to an array
      // which you can use later to use it's exported methods
    });
})