Use AngularJS promise if available

This commit is contained in:
Ibby Hadeed
2017-12-29 10:15:44 -05:00
parent fc9dcc8e64
commit 0cc1a2b2ff
8 changed files with 64 additions and 49 deletions
+15 -2
View File
@@ -2,13 +2,15 @@ import { CordovaOptions } from './interfaces';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
declare const window: any;
export const ERR_CORDOVA_NOT_AVAILABLE = { error: 'cordova_not_available' };
export const ERR_PLUGIN_NOT_INSTALLED = { error: 'plugin_not_installed' };
export function getPromise(callback: Function) {
export function getPromise<T>(callback: (resolve: Function, reject?: Function) => any): Promise<T> {
const tryNativePromise = () => {
if (Promise) {
return new Promise((resolve, reject) => {
return new Promise<T>((resolve, reject) => {
callback(resolve, reject);
});
} else {
@@ -16,6 +18,17 @@ export function getPromise(callback: Function) {
}
};
if (window.angular) {
const injector = window.angular.element(document.querySelector('[ng-app]') || document.body).injector();
if (injector) {
let $q = injector.get('$q');
return $q((resolve: Function, reject: Function) => {
callback(resolve, reject);
});
}
console.warn('Angular 1 was detected but $q couldn\'t be retrieved. This is usually when the app is not bootstrapped on the html or body tag. Falling back to native promises which won\'t trigger an automatic digest when promises resolve.');
}
return tryNativePromise();
}