feat: allow direct scoping of @Injectables to the root injector (#22185)

@Injectable() supports a scope parameter which specifies the target module.
However, it's still difficult to specify that a particular service belongs
in the root injector. A developer attempting to ensure that must either
also provide a module intended for placement in the root injector or target
a module known to already be in the root injector (e.g. BrowserModule).
Both of these strategies are cumbersome and brittle.

Instead, this commit adds a token APP_ROOT_SCOPE which provides a
straightforward way of targeting the root injector directly, without
requiring special knowledge of modules within it.

PR Close #22185
This commit is contained in:
Alex Rickabaugh
2018-02-12 15:23:46 -08:00
committed by Victor Berchet
parent 029dbf0e18
commit 7ac34e42a0
12 changed files with 152 additions and 3 deletions

View File

@ -0,0 +1,27 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Type} from '../type';
import {InjectionToken} from './injection_token';
// APP_ROOT_SCOPE is cast as a Type to allow for its usage as the scope parameter of @Injectable().
/**
* A scope which targets the root injector.
*
* When specified as the `scope` parameter to `@Injectable` or `InjectionToken`, this special
* scope indicates the provider for the service or token being configured belongs in the root
* injector. This is loosely equivalent to the convention of having a `forRoot()` static
* function within a module that configures the provider, and expecting users to only import that
* module via its `forRoot()` function in the root injector.
*
* @experimental
*/
export const APP_ROOT_SCOPE: Type<any> = new InjectionToken<boolean>(
'The presence of this token marks an injector as being the root injector.') as any;