8000 feat($injector): Deferred loading of providers into the injector · Issue #11015 · angular/angular.js · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
feat($injector): Deferred loading of providers into the injector #11015
Closed
@btford

Description

@btford

This is a draft for this feature. I'm still working on the API. Feedback welcome.

Summary

This is a proposal for a new API in Angular that would make it easier for developers to lazy load parts of their application.

This proposal is only for adding loaded providers into a bootstrapped app's injector. It does not include the lazy loading functionality itself, but rather complements module loaders like require.js, webpack, or SystemJS.

Motivations

Developers want to be able to lazy load application code for a variety of reasons. One is to deliver smaller initial payloads. Another is to hide application logic from unprivileged users (think admin panels) as a first layer of security.

Developers are already hacking their own lazy-loading solutions into 1.x, so there's a clear demand for support. Angular 2 will support lazy-loading, so having facilities in Angular 1 means we can write facades that better align APIs (for example, in the new router) and ease migration.

Finally, this API only addresses adding loaded code into Angular's injector, and does not implement lazy loading itself. There are already existing tools that can do this, so we just want to provide a nice API for them to hook into Angular.

Implementation

The implementation would consist of a new method on Angular Modules and a new service.

You would register some placeholder in the injector. Then you use a service to add the provider later.

lazy.js:

var lazyModule = angular.module('lazy', []);
lazyModule.factory('a', );

app.js:

var ngModule = angular.module('app', []);

// names of services that some module will provide
ngModule.placeholder(['a', 'b', 'c']);
ngModule.directivePlaceholder(['myFirstDirective', 'mySecondDirective']);

ngModule.run(function($lazyProvide) {
  $lazyProvide.addModule('lazy'); // or: $lazyProvide.addModule(lazyModuleRef);
});

The only change to the behavior of the injector is that trying to inject a service that only has a placeholder, and not a corresponding provider implementation will throw a new type of error. The injector is still synchronous. HTML that has already been compiled, will not be affected by newly loaded directives.

Placeholders

The goal of this placeholder API is to make it easy to reason about how an app should be put together. Still, it's important that the ability to lazy-load parts of your app isn't prohibitively expensive because the work of adding the placeholders is too much.

The placeholder API is designed so that if a developer is using the AngularJS module system in an idiomatic way, you could statically analyze an app and automatically generate placeholders. ng-annotate already has most of this functionality, so I suspect it'd be easy to add generating placeholders to it.

Okay but I really hate the placeholders thing

You can disable the requirement to have a placeholder before a module is lazily added with the following directive:

<div ng-app="2Cool4SchoolApp" ng-allow-dangerous-lazy-providers>
  <!-- ... -->
</div>

This works the same as ngStrictDi.

If manually bootstrapping, you can use the following bootstrap option:

angular.bootstrap(someElt, ['2Cool4SchoolApp'], {
  allowDangerousLazyProviders: true
});

This is for developers who really know what they're doing, and are willing to maintain the invariants about lazy loading manually.

My goal is to make it so easy to provide placeholders that we can deprecate this API because it's never used. But because there's a clear demand for such an option in the Angular community, I want to make sure that it's possible.

Module redefinition

To avoid situations where it's ambiguous which implementation of a module is used in an app, once an app has been bootstrapped, any modules that include a placeholder cannot be redefined. Trying to redefine a module like this will throw an error:

it('should throw if a module with placeholders is redefined after being bootstrapped', function () {
  angular.module('lazy', []).placeholder(['a', 'b', 'c']);
  angular.bootstrap(document, ['lazy']);
  expect(function () {
    angular.module('lazy', []).placeholder(['d', 'e', 'f']);
  }).toThrow();
});

it('should not throw if a module with placeholders is redefined before being bootstrapped', function () {
  angular.module('lazy', []).placeholder(['a', 'b', 'c']);
  expect(function () {
    angular.module('lazy', []).placeholder(['d', 'e', 'f']);
  }).not.toThrow();
  angular.bootstrap(document, ['lazy']);
  // expect the bootstrapped app to have placeholders for `d`, `e`, `f`.
});

Adding to a module after bootstrap

To avoid situations where it's ambiguous what is actually included in a module, once a module with placeholders has been included in a bootstrapped app, it cannot have new placeholders or providers added to it.

it('should throw if a module has placeholders added after being bootstrapped', function () {
  angular.module('lazy', []).placeholder(['a', 'b', 'c']);
  angular.bootstrap(document, ['lazy']);
  expect(function () {
    angular.module('lazy').placeholder(['d', 'e', 'f']);
  }).toThrow();
  expect(function () {
    angular.module('lazy').factory('foo', function () {});
  }).toThrow();
});

it('should not throw if a module has placeholders added before being bootstrapped', function () {
  angular.module('lazy', []).placeholder(['a', 'b', 'c']);
  expect(function () {
    angular.module('lazy').placeholder(['d', 'e', 'f']);
  }).not.toThrow();
  angular.bootstrap(document, ['lazy']);
  // expect the bootstrapped app to have placeholders for `a`, `b`, `c`, `d`, `e`, and `f`.
});

Loading new code

Loading the provider implementation would be left up to the application developer. It is the responsibility of the developer to make sure that components are loaded at the right time.

For instance, you might use it with ngRoute's resolve:

$routeConfig.when('/', {
  controller: 'MyController',
  resolve: {
    'a': () => $http.get('./lazy.js').then((contents) => {
        // this example is silly
        $injector.addModule(eval(contents));
        return $injector.get('a');
      })
    }
  });

This API intentionally does not include a way to "unload" a service or directive.

Run and config blocks

Lazy loaded modules will not run config blocks:

it('should throw if a module has config blocks', function () {
  angular.module('lazy', []).config(function () {});
  expect(function () {
    $injector.addModule('lazy');
  }).toThrow();
});

But lazily loaded modules will run run blocks when they are loaded.

it('should run run blocks', function () {
  var spy = jasmine.createSpy();
  angular.module('lazy', []).run(spy);
  $injector.addModule('lazy');
  // flush
  expect(spy).toHaveBeenCalled();
});

Risks

The API should mitigate the possibility of making it difficult about the state of the injector. For example, we want developers to be able to distinguish between a case where a user mistyped a provider's name from a case when it was requested before it was loaded. Since compiled templates will not be affected by lazily loaded directives, the compiler should also warn if it compiles a template with placeholder directives, but not their implementation.

On the other hand, the "placeholders" should not require too much upkeep, otherwise this API would be too cumbersome to use. Ideally, the placeholders could be automatically generated at build time.

Prior art

I looked at these lazy-loading solutions:

4F4F

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0