ng-gapi
Version:
Angular 9+ Google api module ng-gapi
126 lines (119 loc) • 3.99 kB
JavaScript
import { __decorate, __param } from 'tslib';
import { InjectionToken, Injectable, Inject, NgModule } from '@angular/core';
import { Observable, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
class GoogleApiConfig {
constructor(clientConfig) {
this.clientConfig = clientConfig;
}
getClientConfig() {
return this.clientConfig;
}
}
let NG_GAPI_CONFIG = new InjectionToken('ng-gapi.config');
let GoogleApiService = class GoogleApiService {
constructor(config) {
this.gapiUrl = 'https://apis.google.com/js/api.js';
this.observers = [];
this.config = new GoogleApiConfig(config);
this.loadGapi().subscribe();
}
onLoad() {
return this.loadGapi();
}
getConfig() {
return this.config;
}
loadGapi() {
return new Observable((observer) => {
if (this.gapiLoaded) {
observer.next(true);
observer.complete();
}
else if (!this.node) {
/**
* script element has not yet been added to document
*/
this.node = document.createElement('script');
this.node.async = true;
this.node.src = this.gapiUrl;
this.node.type = 'text/javascript';
this.node.onload = () => {
this.gapiLoaded = true;
while (this.observers.length) {
const observer = this.observers.shift();
observer.next(true);
observer.complete();
}
this.node = undefined;
};
this.node.onerror = () => {
this.node = undefined;
};
document.getElementsByTagName('head')[0].appendChild(this.node);
}
else {
/**
* script is in the middle of being loaded
*/
this.observers.push(observer);
}
});
}
};
GoogleApiService = __decorate([
Injectable(),
__param(0, Inject(NG_GAPI_CONFIG))
], GoogleApiService);
let GoogleAuthService = class GoogleAuthService {
constructor(googleApi) {
this.googleApi = googleApi;
this.GoogleAuth = undefined;
this.googleApi.onLoad().subscribe(() => {
this.loadGapiAuth().subscribe();
});
}
getAuth(newInstance = false) {
if (!this.GoogleAuth || newInstance) {
return this.googleApi.onLoad()
.pipe(mergeMap(() => this.loadGapiAuth()));
}
return of(this.GoogleAuth);
}
loadGapiAuth() {
return new Observable((observer) => {
gapi.load('auth2', () => {
gapi.auth2.init(this.googleApi.getConfig().getClientConfig()).then((auth) => {
this.GoogleAuth = auth;
observer.next(auth);
observer.complete();
}).catch((err) => observer.error(err));
});
});
}
};
GoogleAuthService = __decorate([
Injectable(),
__param(0, Inject(GoogleApiService))
], GoogleAuthService);
var GoogleApiModule_1;
let GoogleApiModule = GoogleApiModule_1 = class GoogleApiModule {
static forRoot(gapiConfigProvider) {
return {
ngModule: GoogleApiModule_1,
providers: [
gapiConfigProvider,
GoogleAuthService,
GoogleApiService
]
};
}
};
GoogleApiModule = GoogleApiModule_1 = __decorate([
NgModule()
], GoogleApiModule);
/**
* Generated bundle index. Do not edit.
*/
export { GoogleApiConfig, GoogleApiModule, GoogleApiService, GoogleAuthService, NG_GAPI_CONFIG };
//# sourceMappingURL=ng-gapi.js.map