angular-docs-cn/packages/core/src/di/reflective_key.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

/**
* @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
*/
2017-03-02 09:37:01 -08:00
import {stringify} from '../util';
import {resolveForwardRef} from './forward_ref';
2015-05-08 17:57:03 -07:00
2015-04-15 22:35:38 +00:00
/**
* A unique object used for retrieving items from the {@link ReflectiveInjector}.
2015-04-15 22:35:38 +00:00
*
* Keys have:
* - a system-wide unique `id`.
2015-09-21 13:41:52 -07:00
* - a `token`.
2015-04-15 22:35:38 +00:00
*
* `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
* the
2015-09-21 13:41:52 -07:00
* injector to store created objects in a more efficient way.
*
* `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
* resolving
* providers.
* @deprecated No replacement
2015-04-15 22:35:38 +00:00
*/
export class ReflectiveKey {
public readonly displayName: string;
2015-09-21 13:41:52 -07:00
/**
* Private
*/
2015-06-17 10:12:06 +02:00
constructor(public token: Object, public id: number) {
if (!token) {
throw new Error('Token must be defined!');
}
this.displayName = stringify(this.token);
}
2015-04-15 22:35:38 +00:00
/**
* Retrieves a `Key` for a token.
2015-04-15 22:35:38 +00:00
*/
static get(token: Object): ReflectiveKey {
return _globalKeyRegistry.get(resolveForwardRef(token));
}
2014-10-20 15:17:06 -04:00
2015-04-15 22:35:38 +00:00
/**
* @returns the number of keys registered in the system.
2015-04-15 22:35:38 +00:00
*/
static get numberOfKeys(): number { return _globalKeyRegistry.numberOfKeys; }
2014-10-09 12:09:50 -04:00
}
export class KeyRegistry {
private _allKeys = new Map<Object, ReflectiveKey>();
get(token: Object): ReflectiveKey {
if (token instanceof ReflectiveKey) return token;
2015-06-17 21:42:56 -07:00
if (this._allKeys.has(token)) {
return this._allKeys.get(token) !;
}
const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
this._allKeys.set(token, newKey);
return newKey;
}
get numberOfKeys(): number { return this._allKeys.size; }
}
const _globalKeyRegistry = new KeyRegistry();