从代码中动态导入@Angular/http

从代码中动态导入@Angular/http,angular,import,libraries,Angular,Import,Libraries,有没有办法不使用著名的 import { Http } from '@angular/http' 我想以编程方式导入@angular/http或任何其他库。 有什么想法吗?如果您想动态访问模块,可以使用require要求有一个参数字符串模块名称 import { Component } from '@angular/core'; declare var require: any // use http anywhere in your project // if need to access

有没有办法不使用著名的

import { Http } from '@angular/http'
我想以编程方式导入@angular/http或任何其他库。
有什么想法吗?

如果您想动态访问模块,可以使用
require
<代码>要求有一个参数<代码>字符串模块名称

import { Component } from '@angular/core';

declare var require: any
// use http anywhere in your project
// if need to access all the functions from http module by using .
export const http = require('@angular/common/http');

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'demong';

  constructor() {

  }
}
您还可以通过以下方式在运行时动态获取模块:

export class Demo {
   getModule(moduleName: string) {
       return require(moduleName);
   }
}

您还可以将导入用作一项功能:

可以调用import关键字作为函数来动态导入 模块。当以这种方式使用时,它会返回一个承诺


资料来源:

你在这里想要实现什么?为什么会有这样的要求?我已经做了一个已经发布的AngularCore应用程序。现在,这个核心应用程序从特定路径动态加载模块。加载模块时,其中一个模块需要@angular/http,因此我想直接从编解码器导入此库。对此,您是否可以使用
require
。我是新来的Angular这还需要你在构建时知道模块的名称吗?如果直到运行时才知道模块名,那么这段代码是否有效?最后一段代码将在这方面帮助您。将此视为工厂设计模式,提供模块的名称字符串,如果该模块可用,您将得到该对象。
import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });