简体   繁体   中英

How do you properly configure a provider service in Angular.js

What is the best practices or patterns to config a provider inside a config block like how $locationProvider and $routeProvider do?

As far as I know, only providers are configurable inside config blocks.

The following code block is how I want to do with my own custom provider.

.config([
  '$routeProvider', '$locationProvider', '$httpProvider',
  function ($routeProvider, $locationProvider, $httpProvider) {
    $locationProvider
      .html5Mode(true)
      .hashPrefix('!');

    $routeProvider.otherwise({
      redirectTo: '/'
    });

    $httpProvider.defaults.withCredentials = true;
  }
])

There is a very good explanations on providers, factories and services at the official docs .

In a nutshell, you should create a provider and expose whatever methods you need, besides the $get method. Upon the config call, you can call any other method you have, and when the system inject the dependency, it's going to call the $get method.

Assembled a simple Plnkr here , but that's how it's goes:

1. The provider

app.provider('myService', function() {
  var configuredValue;

  this.setValue = function(val) {
    configuredValue = val;
  };

  this.$get = function() {
    return {
      valueSettedByTheConfig: configuredValue
    };
  };
});

Here you created the provider for the myService service, exposing a setValue configuration method, as in $locationProvider.html5Mode or $routeProvider.otherwise .

2. The configuration moment

app.config(function(myServiceProvider) {
  myServiceProvider.setValue('my configured value');
});

Here you configure you module, before it gets used, by calling the exposed setValue method.

Notice that we inject the provider ( myService*Provider* ), for during configuration phase, you can only inject providers, not services.

3. The usage

app.controller('MainCtrl', function($scope, myService) {
  $scope.name = myService.valueSettedByTheConfig;
});

And finally here you simply inject the service and Angular is going to call the provider's $get method to generate the instance, after the config phase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM