Angular 中的提供者和实例有什么区别?

What is the difference between provider and instances in Angular?

我是 Angular 的新手。我正在研究配置块和 运行 模块块。

请看下面的代码:

angular.module('myModule', []).
config(function(injectables) { // provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
});

正如您在配置块中看到的那样:"You can only inject Providers (not instances)"。

这是什么意思?谁能解释一下提供者和实例之间的区别是什么?

从这个 post 中窃取:AngularJS: Service vs provider vs factory - 绝对值得一读,以便更好地理解 angular 中可用的不同类型提供程序的作用。

But what if we wanted to configure the Greeter class before the injection? Then we could write

For example:

provide.provider('greeter2', function() {
  var salutation = 'Hello';
  this.setSalutation = function(s) {
  salutation = s;
}

  function Greeter(a) {
    this.greet = function() {
      return salutation + ' ' + a;
    }
  }

  this.$get = function(a) { //When injected into a controller or service, this is what will get called.
    return new Greeter(a);
  };
});

Then you can configure the above like so:

angular.module('abc', []).config(function(greeter2Provider) { //Provider injected
  greeter2Provider.setSalutation('Halo');
});

function Controller(greeter2) { //Accessing the actual service exposed by the provider.$get
  expect(greeter2.greet()).toEqual('Halo 123');
}

其实你的问题很好。为了简单起见,我们在 Angular JS 中定义服务来实现我们的功能。 Provider 是配置服务工作方式的一种方式。 Angular JS 中还有一些概念,即 Values、Constants、Factory、Service 和 Decorator,可以帮助我们以不同的方式拦截服务。请检查以下 link.

https://docs.angularjs.org/guide/providers

回到提供者,它们用于定义应用程序范围的配置,这些配置甚至需要在应用程序启动之前完成。由于配置块在 Angular JS 模块加载之前执行,我们在它们下配置提供程序。由于到那时还没有加载模块,因此您无法访问配置块内的服务。

一旦 $injector 加载了所有模块,就会执行

运行 块。一旦你输入 运行 块,你就不能再配置你的提供者,因为你的服务无论如何都会被加载。这就是您无法在 运行 块中访问提供程序的原因。

让我们看一个例子。我设计我的应用程序以支持用户和管理屏幕。但是与它们相关的特性是在各自的服务中定义的。我只想在用户登录时加载适当的服务。我们使用如下提供程序实现了这一点。

定义角色提供者

myApp.provider("roles", function rolesProvider(){
var role;
this.setRole = function(value) {
role = value;
}

this.$get = function rolesFactory() {
if(role === "user") {
return new userRole();
} else {
return new adminRole();
}
}
});

将 rolesProvider 配置为用户

myApp.config(["rolesProvider"], function(rulesProvider){
rulesProvider.setRole("user"); 
});

我的应用程序将被配置为 运行 在应用程序启动时作为用户而不是管理员。

如果您需要更多解释,请告诉我。

快速回答:提供商将创建一个实例。在他们这样做之前,您可以在 config() 块中使用它们。对于要在启动期间更改 url 端点的数据提供者非常有用。

但是您可以 运行 在 "Provider provider" 部分的一些配置代码,在 new Something() 之前是 运行。

Service Service、Service Factory 和 Service Value 都是 Provider 定义的快捷方式,但是隐藏了配置部分,直接对对象进行实例化(使用 new Something())。