如何在angular中创建可插拔应用程序? [英] How to create a pluggable application in angular?

查看:89
本文介绍了如何在angular中创建可插拔应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个应用程序,该应用程序可以分为多个模块,每个模块都有自己的路由.用户可以从应用程序主模块打开和关闭这些模块.

I want to create an application which can be divided in multiple module with their own routing and all. And user can turn on and off these modules from application main module.

  1. 我是否必须加载所有模块,并根据用户是否已订阅禁用该模块.我认为这会减慢应用程序的加载速度,因为会加载所有模块代码并在应用程序引导时注入.
  2. 这个问题还有其他选择吗?

推荐答案

应为主模块提供已启用模块的列表:

The list of enabled modules should be provided for main module:

var enabledModules = [...];

angular.module('app', ['thirdParty', 'app.common'].concat(enabledModules));

很显然,enabledModules数组无法正常加载$http,因为此时应用程序尚未启动.可以使用XHR或服务器端模板进行定义.

Obviously, enabledModules array can't be normally loaded with $http, because the application isn't bootstrapped at this point. XHR or server-side templating may be be used to define it.

或者,可以使用单独的应用程序加载先决条件.由于使用了DI,因此可以对其进行彻底的测试.

Alternatively, a separate application can be used to load prerequisites. Due to the use of DI, it can be thoroughly tested.

angular.module('app', ['thirdParty', 'app.common']);

angular.module('appInitializer', [])
.factory('loader', ($http) => {
  return $http.get('enabled-modules').then((result) => result.data);
})
.factory('initializer', (loader, $document) => {
  return loader.then((enabledModules) => {
    $document.ready(() => {
      angular.bootstrap($document.find('body'), ['app'].concat(enabledModules));
    });
  });
});

angular.injector(['ng', 'appInitializer'])
.get('initializer')
.catch((err) => console.error(err));

这篇关于如何在angular中创建可插拔应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆