Import gapi.auth2 into angular 2 typescript

I tried to import some classes or functions from Google gapi.auth2 into typescript. But below code never works, even I correctly added gapi.auth2 types to the typing directory.

import { GoogleAuth } from 'gapi.auth2';

I always had an error:

Error TS2307: Cannot find module 'gapi.auth2'

Should I use some kind of relative directory search like "../../typings/gapi.auth2"?

Or maybe the way I use is not true?

Thank!

+15
source share
3 answers

To use gapiand gapi.authwith Angular2, set script type definitions using NPM.

npm install --save @types/gapi
npm install --save @types/gapi.auth2

: @types/gapi @types/gapi.auth2 node_modules package.json.

node_modules, . Angular2 , :

main-app/
  node_modules/
    @types/
      gapi/
      gapi.auth2/

tsconfig.json, gapi gapi.auth2 ( ):

{
  "compileOnSave": false,
  "compilerOptions": {
    "types": ["gapi", "gapi.auth2"]
  }
}

Typescript , Node.js :

[...] . Node node_modules. node_modules , . Node , node_modules, , .

Angular2 ( , gapi gapi.auth2).

, gapi gapi.auth2 TypeScript, .ts, npm install ( , /// oherwise you ' ):

/// <reference path="../../node_modules/@types/gapi/index.d.ts" />

, , .ts , TypeScript.

TypeScript Node, .ts, Angular2 gapi . declare var gapi: any; .ts , . :

// You may not have this explicit reference.
/// <reference path="../../node_modules/@types/gapi/index.d.ts" />
import { NgZone, Injectable, Optional } from '@angular/core';
declare var gapi: any;

(https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/gapi/index.d.ts), . , , .

JavaScript Typescript , , .

gapi ( Angular):

 loadClient(): Promise<any> {
     return new Promise((resolve, reject) => {
         this.zone.run(() => {
                gapi.load('client', {
                    callback: resolve,
                    onerror: reject,
                    timeout: 1000, // 5 seconds.
                    ontimeout: reject
                });
         });
    });
}

...

-, , gapi.load , . GAPI:

  • , , .
  • , . .

- . , , , , .

-, gapi.load

this.zone.run(() => {
  // gapi.load
});

NgZone.run

zone.run Angular , Angular [...]

, , gapi.load Angular. , , .

-, loadClient() , , , gapi.load. , loadClient Angular, apiLoaderServce, ngOnInit gapi:

ngOnInit(): void {
    this.apiLoaderService.loadClient().then(
        result => this.apiLoaded = true,
        err => this.apiLoaded = false
    );
}

gapi.load , gapi.client , JavaScript API, OAuth, (API) API:

initClient(): Promise<any> {
    var API_KEY = // Your API key.
    var DISCOVERY_DOC = // Your discovery doc URL.
    var initObj = {
        'apiKey': API_KEY,
        'discoveryDocs': [DISCOVERY_DOC],
    };

    return new Promise((resolve, reject) => {
        this.zone.run(() => {
            gapi.client.init(initObj).then(resolve, reject);
        });
    });
}

, NgZone.run Angular.

loadClient() initClient() Angular. Angular ( ) ngOnInit:

ngOnInit(): void {
    this.apiLoaderService.loadClient().then(
        result => {
            this.apiLoaded = true;
            return this.apiLoaderService.initClient()
        },
        err => {
            this.apiFailed = true;
        }
    ).then(result => {
        this.apiReady = true;
    }, err => {
        this.apiFailed = true;
    });
}

, gapi script .

<html>
  <head>
    <script src="https://apis.google.com/js/api.js"></script>

async defer, , Angular 2 , .

<!-- This will not work. -->
<html>
  <head>
    <script async defer src="https://apis.google.com/js/api.js"></script>

, , gapi /main-app/src/assests :

    <html>
      <head>
        <script src="assets/api.js"></script>

. Google https://apis.google.com/js/api.js, . . //apis.google.com/js/ .

+41

@Jack RxJS. Angular 2, Angular 5 , - .

  1. , npm.

    npm install --save @types/gapi
    npm install --save @types/gapi.auth2
    
  2. tsconfig.json. , tsconfig.app.json tsconfig.spec.json. tsconfig.json, , , . :

    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "gapi",
      "gapi.auth2"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
    
  3. Google platform.js. index.html. async defer, @Jack.

    <script src="https://apis.google.com/js/platform.js"></script>
    
  4. . :

    import { Injectable, NgZone, Output } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { BehaviorSubject } from 'rxjs';
    import { HttpClient } from '@angular/common/http';
    import { User } from './User';
    
    @Injectable()
    export class AuthenticatorService {
        public auth2: any;
        public user$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
        public isLoggedIn$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
        public isLoaded$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    
        constructor(private zone: NgZone, private http: HttpClient) { }
    
        validateToken(token: string): Observable<User> {
            return this.http.get<User>('http://yourServer:3000/validationApi/${token}');
        }
    
        signIn(): void {
            this.auth2.signIn().then(user => {
                this.validateToken(user.getAuthResponse().id_token).subscribe(user => {
                    this.zone.run(() => {
                        this.user$.next(user);
                        this.isLoggedIn$.next(true);
                    });
                },
                    (err) => {
                        console.error(err);
                    });
            });
        };
    
        signOut(): void {
            this.auth2.signOut().then(() => {
                this.zone.run(() => {
                    this.isLoggedIn$.next(false);
                    this.user$.next(null);
                });
            },
                (err) => {
                    console.error(err);
                });
        }
    
        loadAuth2(): void {
            gapi.load('auth2', () => {
                gapi.auth2.init({
                    client_id: 'yourClientId',
                    fetch_basic_profile: true
                }).then((auth) => {
                    this.zone.run(() => {
                        this.auth2 = auth;
                        this.isLoaded$.next(true);
                    });
                },
                );
            });
        }
    }
    

. RxJS BehaviorSubjects. . loadAuth2 Google gapi.auth2.GoogleAuth. Google, . , this.zone.run, GoogleAuth. NgZone . RxJS BehaviorSubject isLoaded$ true. signIn() signOut() functions-, NgZone BehaviorSubject.

  1. , , . . :

    import { Component, OnInit } from '@angular/core';
    import { AuthenticatorService } from  '../authenticator.service'
    import { User } from '../User';
    
    
    @Component({
    selector: 'sign-in',
    template: '
        <ng-container *ngIf="authIsLoaded">
             <button *ngIf="!isLoggedIn" (click)="signIn()">Sign In With Google</button>
            <button *ngIf="isLoggedIn" (click)="signOut()">Sign Out</button>
        </ng-container>
        <h2 *ngIf="authIsLoaded && isLoggedIn"> Signed in as {{user.name}} </h2>'
    })
    export class GoogleAuthenticatorComponent implements OnInit {
    
    public authIsLoaded: boolean = false;
    public isLoggedIn: boolean = false;
    public user: User;
    
    constructor(private authenticatorService: AuthenticatorService) { }
    
        signIn(): void {
        this.authenticatorService.signIn();
        };
    
        signOut(): void {
        this.authenticatorService.signOut();
        }
    
        ngOnInit() {
        this.authenticatorService.isLoaded$.subscribe( value => {
            this.authIsLoaded = value;
        });
    
        this.authenticatorService.isLoggedIn$.subscribe( value => {
            this.isLoggedIn = value;
        });
    
        this.authenticatorService.user$.subscribe( value => {
            this.user = value;
        });
    
        this.authenticatorService.loadAuth2();
        }
    }
    

ngOnInit. AuthenticatorService .

, - gapi.auth2 .

+6

Source: https://habr.com/ru/post/1655434/


All Articles