mirror of
https://github.com/danielsogl/awesome-cordova-plugins.git
synced 2026-05-02 00:07:23 +08:00
Use AngularJS promise if available
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user