PageRenderTime 25ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/@angular/core/esm/src/application_ref.js

https://gitlab.com/hashmi.smf/routingangular2
JavaScript | 351 lines | 266 code | 0 blank | 85 comment | 24 complexity | bcbb40ff44a8d43c91f8b22cd3fb3990 MD5 | raw file
  1. import { ObservableWrapper, PromiseWrapper } from '../src/facade/async';
  2. import { ListWrapper } from '../src/facade/collection';
  3. import { BaseException, ExceptionHandler, unimplemented } from '../src/facade/exceptions';
  4. import { IS_DART, assertionsEnabled, isBlank, isPresent, isPromise, lockMode } from '../src/facade/lang';
  5. import { APP_INITIALIZER, PLATFORM_INITIALIZER } from './application_tokens';
  6. import { Console } from './console';
  7. import { Injectable, Injector } from './di';
  8. import { ComponentResolver } from './linker/component_resolver';
  9. import { wtfCreateScope, wtfLeave } from './profile/profile';
  10. import { Testability, TestabilityRegistry } from './testability/testability';
  11. import { NgZone } from './zone/ng_zone';
  12. /**
  13. * Create an Angular zone.
  14. * @experimental
  15. */
  16. export function createNgZone() {
  17. return new NgZone({ enableLongStackTrace: assertionsEnabled() });
  18. }
  19. var _platform;
  20. var _inPlatformCreate = false;
  21. /**
  22. * Creates a platform.
  23. * Platforms have to be eagerly created via this function.
  24. * @experimental
  25. */
  26. export function createPlatform(injector) {
  27. if (_inPlatformCreate) {
  28. throw new BaseException('Already creating a platform...');
  29. }
  30. if (isPresent(_platform) && !_platform.disposed) {
  31. throw new BaseException('There can be only one platform. Destroy the previous one to create a new one.');
  32. }
  33. lockMode();
  34. _inPlatformCreate = true;
  35. try {
  36. _platform = injector.get(PlatformRef);
  37. }
  38. finally {
  39. _inPlatformCreate = false;
  40. }
  41. return _platform;
  42. }
  43. /**
  44. * Checks that there currently is a platform
  45. * which contains the given token as a provider.
  46. * @experimental
  47. */
  48. export function assertPlatform(requiredToken) {
  49. var platform = getPlatform();
  50. if (isBlank(platform)) {
  51. throw new BaseException('No platform exists!');
  52. }
  53. if (isPresent(platform) && isBlank(platform.injector.get(requiredToken, null))) {
  54. throw new BaseException('A platform with a different configuration has been created. Please destroy it first.');
  55. }
  56. return platform;
  57. }
  58. /**
  59. * Dispose the existing platform.
  60. * @experimental
  61. */
  62. export function disposePlatform() {
  63. if (isPresent(_platform) && !_platform.disposed) {
  64. _platform.dispose();
  65. }
  66. }
  67. /**
  68. * Returns the current platform.
  69. * @experimental
  70. */
  71. export function getPlatform() {
  72. return isPresent(_platform) && !_platform.disposed ? _platform : null;
  73. }
  74. /**
  75. * Shortcut for ApplicationRef.bootstrap.
  76. * Requires a platform to be created first.
  77. * @experimental
  78. */
  79. export function coreBootstrap(componentFactory, injector) {
  80. var appRef = injector.get(ApplicationRef);
  81. return appRef.bootstrap(componentFactory);
  82. }
  83. /**
  84. * Resolves the componentFactory for the given component,
  85. * waits for asynchronous initializers and bootstraps the component.
  86. * Requires a platform to be created first.
  87. * @experimental
  88. */
  89. export function coreLoadAndBootstrap(componentType, injector) {
  90. var appRef = injector.get(ApplicationRef);
  91. return appRef.run(() => {
  92. var componentResolver = injector.get(ComponentResolver);
  93. return PromiseWrapper
  94. .all([componentResolver.resolveComponent(componentType), appRef.waitForAsyncInitializers()])
  95. .then((arr) => appRef.bootstrap(arr[0]));
  96. });
  97. }
  98. /**
  99. * The Angular platform is the entry point for Angular on a web page. Each page
  100. * has exactly one platform, and services (such as reflection) which are common
  101. * to every Angular application running on the page are bound in its scope.
  102. *
  103. * A page's platform is initialized implicitly when {@link bootstrap}() is called, or
  104. * explicitly by calling {@link createPlatform}().
  105. * @stable
  106. */
  107. export class PlatformRef {
  108. /**
  109. * Retrieve the platform {@link Injector}, which is the parent injector for
  110. * every Angular application on the page and provides singleton providers.
  111. */
  112. get injector() { throw unimplemented(); }
  113. ;
  114. get disposed() { throw unimplemented(); }
  115. }
  116. export class PlatformRef_ extends PlatformRef {
  117. constructor(_injector) {
  118. super();
  119. this._injector = _injector;
  120. /** @internal */
  121. this._applications = [];
  122. /** @internal */
  123. this._disposeListeners = [];
  124. this._disposed = false;
  125. if (!_inPlatformCreate) {
  126. throw new BaseException('Platforms have to be created via `createPlatform`!');
  127. }
  128. let inits = _injector.get(PLATFORM_INITIALIZER, null);
  129. if (isPresent(inits))
  130. inits.forEach(init => init());
  131. }
  132. registerDisposeListener(dispose) { this._disposeListeners.push(dispose); }
  133. get injector() { return this._injector; }
  134. get disposed() { return this._disposed; }
  135. addApplication(appRef) { this._applications.push(appRef); }
  136. dispose() {
  137. ListWrapper.clone(this._applications).forEach((app) => app.dispose());
  138. this._disposeListeners.forEach((dispose) => dispose());
  139. this._disposed = true;
  140. }
  141. /** @internal */
  142. _applicationDisposed(app) { ListWrapper.remove(this._applications, app); }
  143. }
  144. /** @nocollapse */
  145. PlatformRef_.decorators = [
  146. { type: Injectable },
  147. ];
  148. /** @nocollapse */
  149. PlatformRef_.ctorParameters = [
  150. { type: Injector, },
  151. ];
  152. /**
  153. * A reference to an Angular application running on a page.
  154. *
  155. * For more about Angular applications, see the documentation for {@link bootstrap}.
  156. * @stable
  157. */
  158. export class ApplicationRef {
  159. /**
  160. * Retrieve the application {@link Injector}.
  161. */
  162. get injector() { return unimplemented(); }
  163. ;
  164. /**
  165. * Retrieve the application {@link NgZone}.
  166. */
  167. get zone() { return unimplemented(); }
  168. ;
  169. /**
  170. * Get a list of component types registered to this application.
  171. */
  172. get componentTypes() { return unimplemented(); }
  173. ;
  174. }
  175. export class ApplicationRef_ extends ApplicationRef {
  176. constructor(_platform, _zone, _injector) {
  177. super();
  178. this._platform = _platform;
  179. this._zone = _zone;
  180. this._injector = _injector;
  181. /** @internal */
  182. this._bootstrapListeners = [];
  183. /** @internal */
  184. this._disposeListeners = [];
  185. /** @internal */
  186. this._rootComponents = [];
  187. /** @internal */
  188. this._rootComponentTypes = [];
  189. /** @internal */
  190. this._changeDetectorRefs = [];
  191. /** @internal */
  192. this._runningTick = false;
  193. /** @internal */
  194. this._enforceNoNewChanges = false;
  195. var zone = _injector.get(NgZone);
  196. this._enforceNoNewChanges = assertionsEnabled();
  197. zone.run(() => { this._exceptionHandler = _injector.get(ExceptionHandler); });
  198. this._asyncInitDonePromise = this.run(() => {
  199. let inits = _injector.get(APP_INITIALIZER, null);
  200. var asyncInitResults = [];
  201. var asyncInitDonePromise;
  202. if (isPresent(inits)) {
  203. for (var i = 0; i < inits.length; i++) {
  204. var initResult = inits[i]();
  205. if (isPromise(initResult)) {
  206. asyncInitResults.push(initResult);
  207. }
  208. }
  209. }
  210. if (asyncInitResults.length > 0) {
  211. asyncInitDonePromise =
  212. PromiseWrapper.all(asyncInitResults).then((_) => this._asyncInitDone = true);
  213. this._asyncInitDone = false;
  214. }
  215. else {
  216. this._asyncInitDone = true;
  217. asyncInitDonePromise = PromiseWrapper.resolve(true);
  218. }
  219. return asyncInitDonePromise;
  220. });
  221. ObservableWrapper.subscribe(zone.onError, (error) => {
  222. this._exceptionHandler.call(error.error, error.stackTrace);
  223. });
  224. ObservableWrapper.subscribe(this._zone.onMicrotaskEmpty, (_) => { this._zone.run(() => { this.tick(); }); });
  225. }
  226. registerBootstrapListener(listener) {
  227. this._bootstrapListeners.push(listener);
  228. }
  229. registerDisposeListener(dispose) { this._disposeListeners.push(dispose); }
  230. registerChangeDetector(changeDetector) {
  231. this._changeDetectorRefs.push(changeDetector);
  232. }
  233. unregisterChangeDetector(changeDetector) {
  234. ListWrapper.remove(this._changeDetectorRefs, changeDetector);
  235. }
  236. waitForAsyncInitializers() { return this._asyncInitDonePromise; }
  237. run(callback) {
  238. var zone = this.injector.get(NgZone);
  239. var result;
  240. // Note: Don't use zone.runGuarded as we want to know about
  241. // the thrown exception!
  242. // Note: the completer needs to be created outside
  243. // of `zone.run` as Dart swallows rejected promises
  244. // via the onError callback of the promise.
  245. var completer = PromiseWrapper.completer();
  246. zone.run(() => {
  247. try {
  248. result = callback();
  249. if (isPromise(result)) {
  250. PromiseWrapper.then(result, (ref) => { completer.resolve(ref); }, (err, stackTrace) => {
  251. completer.reject(err, stackTrace);
  252. this._exceptionHandler.call(err, stackTrace);
  253. });
  254. }
  255. }
  256. catch (e) {
  257. this._exceptionHandler.call(e, e.stack);
  258. throw e;
  259. }
  260. });
  261. return isPromise(result) ? completer.promise : result;
  262. }
  263. bootstrap(componentFactory) {
  264. if (!this._asyncInitDone) {
  265. throw new BaseException('Cannot bootstrap as there are still asynchronous initializers running. Wait for them using waitForAsyncInitializers().');
  266. }
  267. return this.run(() => {
  268. this._rootComponentTypes.push(componentFactory.componentType);
  269. var compRef = componentFactory.create(this._injector, [], componentFactory.selector);
  270. compRef.onDestroy(() => { this._unloadComponent(compRef); });
  271. var testability = compRef.injector.get(Testability, null);
  272. if (isPresent(testability)) {
  273. compRef.injector.get(TestabilityRegistry)
  274. .registerApplication(compRef.location.nativeElement, testability);
  275. }
  276. this._loadComponent(compRef);
  277. let c = this._injector.get(Console);
  278. if (assertionsEnabled()) {
  279. let prodDescription = IS_DART ? 'Production mode is disabled in Dart.' :
  280. 'Call enableProdMode() to enable the production mode.';
  281. c.log(`Angular 2 is running in the development mode. ${prodDescription}`);
  282. }
  283. return compRef;
  284. });
  285. }
  286. /** @internal */
  287. _loadComponent(componentRef) {
  288. this._changeDetectorRefs.push(componentRef.changeDetectorRef);
  289. this.tick();
  290. this._rootComponents.push(componentRef);
  291. this._bootstrapListeners.forEach((listener) => listener(componentRef));
  292. }
  293. /** @internal */
  294. _unloadComponent(componentRef) {
  295. if (!ListWrapper.contains(this._rootComponents, componentRef)) {
  296. return;
  297. }
  298. this.unregisterChangeDetector(componentRef.changeDetectorRef);
  299. ListWrapper.remove(this._rootComponents, componentRef);
  300. }
  301. get injector() { return this._injector; }
  302. get zone() { return this._zone; }
  303. tick() {
  304. if (this._runningTick) {
  305. throw new BaseException('ApplicationRef.tick is called recursively');
  306. }
  307. var s = ApplicationRef_._tickScope();
  308. try {
  309. this._runningTick = true;
  310. this._changeDetectorRefs.forEach((detector) => detector.detectChanges());
  311. if (this._enforceNoNewChanges) {
  312. this._changeDetectorRefs.forEach((detector) => detector.checkNoChanges());
  313. }
  314. }
  315. finally {
  316. this._runningTick = false;
  317. wtfLeave(s);
  318. }
  319. }
  320. dispose() {
  321. // TODO(alxhub): Dispose of the NgZone.
  322. ListWrapper.clone(this._rootComponents).forEach((ref) => ref.destroy());
  323. this._disposeListeners.forEach((dispose) => dispose());
  324. this._platform._applicationDisposed(this);
  325. }
  326. get componentTypes() { return this._rootComponentTypes; }
  327. }
  328. /** @internal */
  329. ApplicationRef_._tickScope = wtfCreateScope('ApplicationRef#tick()');
  330. /** @nocollapse */
  331. ApplicationRef_.decorators = [
  332. { type: Injectable },
  333. ];
  334. /** @nocollapse */
  335. ApplicationRef_.ctorParameters = [
  336. { type: PlatformRef_, },
  337. { type: NgZone, },
  338. { type: Injector, },
  339. ];
  340. export const PLATFORM_CORE_PROVIDERS =
  341. /*@ts2dart_const*/ [
  342. PlatformRef_,
  343. /*@ts2dart_const*/ (
  344. /* @ts2dart_Provider */ { provide: PlatformRef, useExisting: PlatformRef_ })
  345. ];
  346. export const APPLICATION_CORE_PROVIDERS = [
  347. /* @ts2dart_Provider */ { provide: NgZone, useFactory: createNgZone, deps: [] },
  348. ApplicationRef_,
  349. /* @ts2dart_Provider */ { provide: ApplicationRef, useExisting: ApplicationRef_ },
  350. ];
  351. //# sourceMappingURL=application_ref.js.map