AngularJS 服务何时重新初始化?

When is an AngularJS service re-initialized?

angularjs 中的服务(或工厂)的生命周期是多少?什么时候重新初始化?

Services/factories只初始化一次,第一次使用。来自文档:https://docs.angularjs.org/guide/services

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

当Angular引导时,它将服务的构造函数附加到相关模块。这种情况发生过一次。

angular
  .module('myApp')
  .service('User', function UserConstructor() {
    // stuff
  });

当您尝试 运行 控制器或依赖于特定服务的东西时,Angular 会为您注入它。

app.controller('FirstCtrl', function FirstCtrlConstructor(User) {
  // User is available here
});

在幕后,angular 使用这个叫做 $injector 的东西为您做依赖注入。它的工作原理是这样的:

var $injector = {};
$injector.cached = [];
$injector.get = function(service) {
  // check if service is in this.cached
    // if so, return it
    // if not
      // 1) instantiate the service
      // 2) store it in this.cached
      // 3) return it
};

所以当Angular看到它需要将User注入FirstCtrlConstructor时,它调用$injector.get('User')来获取User。由于它之前没有在其他任何地方注入 User,它将达到 "if not" 条件并且:

  1. 呼叫new User().
  2. 保存在$injector.cached中,下次使用。
  3. Return吧。

现在假设我们需要第二次注入User

app.controller('SecondCtrl', function SecondCtrlConstructor(User) {
  // stuff
});

同样,当 Angular 发现 SecondCtrlConstructor 依赖于 User 时,它调用 $injector.get('User') 来获取 User 以便它可以注入它。这次,它遇到了 "if so" 条件。由于我们之前将 User 放在 $injector.cached 中,它为我们找到了它。因此,User 不会再次实例化。

假设我们有一个 ThirdCtrl,它也依赖于 User。它也会在 $injector.cached 中找到它,因此它不会实例化 UserConstructor。假设我们有 myDirective 依赖于 User。同样的事情会发生——它会在 $injector.cached 中找到它,因此不会实例化它。

这叫做Singleton pattern。当您不想多次实例化某物时使用它。 Angular 将其用于服务,因此它们不会被多次实例化。工厂也是如此(供应商可能也是如此;值和常量可能并非如此)。

有关更多信息,请参阅 https://medium.com/@adamzerner/dependency-injection-in-angular-18490a9a934