Giter Site home page Giter Site logo

ng-gapi's Introduction

Angular 9+ Google api module (ng-gapi)

This module will add the google api to your project. It wraps the Gapi in to a service layer allowing to work with Gapi in a Angular 9+ project.

made by codeforges

Latest News

We have started to work on our video tutorials series, Angular + NestJs a full fledged application.

Latest change

  • Requires now Typescript version 3.8.3 or higher
  • Requires Angular9 or higher

Installation

npm install ng-gapi

Usage

DEMO stackblitz

To use the ng-gapi simply add GoogleApiModule to your module imports and set the configuration.

ClientConfig interface

Bellow are all available parameters that can be provided in the forRoot() method.

export interface NgGapiClientConfig extends ClientConfig {
    discoveryDocs: string[];
}


//And the extended ClientConfig
interface ClientConfig {
    /**
     * The app's client ID, found and created in the Google Developers Console.
     */
    client_id?: string;

    /**
     * The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none.
     * Defaults to single_host_origin if unspecified.
     */
    cookie_policy?: string;

    /**
     * The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false.
     */
    scope?: string;

    /**
     * Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified.
     */
    fetch_basic_profile?: boolean;

    /**
     * The Google Apps domain to which users must belong to sign in. This is susceptible to modification by clients,
     * so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client,
     * and the hd claim in the ID Token on the server to verify the domain is what you expected.
     */
    hosted_domain?: string;

    /**
     * Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0,
     * as described in <a href="https://developers.google.com/accounts/docs/OpenID#openid-connect">OpenID 2.0 (Migration)</a>.
     */
    openid_realm?: string;

    /**
     * The UX mode to use for the sign-in flow.
     * By default, it will open the consent flow in a popup.
     */
    ux_mode?: "popup" | "redirect";

    /**
     * If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow.
     * The default redirect_uri is the current URL stripped of query parameters and hash fragment.
     */
    redirect_uri?: string;
  }
Example:
import {
    GoogleApiModule, 
    GoogleApiService, 
    GoogleAuthService, 
    NgGapiClientConfig, 
    NG_GAPI_CONFIG,
    GoogleApiConfig
} from "ng-gapi";

let gapiClientConfig: NgGapiClientConfig = {
    client_id: "CLIENT_ID",
    discoveryDocs: ["https://analyticsreporting.googleapis.com/$discovery/rest?version=v4"],
    scope: [
        "https://www.googleapis.com/auth/analytics.readonly",
        "https://www.googleapis.com/auth/analytics"
    ].join(" ")
};

@NgModule({
    imports: [
        //...
          GoogleApiModule.forRoot({
            provide: NG_GAPI_CONFIG,
            useValue: gapiClientConfig
          }),
        //...
    ]
})
export MyModule {}

Now you will have Access to the GoogleApi service. The service has a a event method onLoad(callback) This event will fire when the gapi script is loaded.

Usage example :

export class FooService {
    constructor(gapiService: GoogleApiService) {
        gapiService.onLoad().subscribe(()=> {
           // Here we can use gapi
           
        });
    }
}

Also check the example folder with a google api reports module

GoogleAuthService

The module has a GoogleAuth service which allows you to work with the google auth

Usage:

//Example of a UserService 

@Injectable()
export class UserService {
    public static SESSION_STORAGE_KEY: string = 'accessToken';
    private user: GoogleUser;
    
    constructor(private googleAuth: GoogleAuthService){ 
    }
    
    public getToken(): string {
        let token: string = sessionStorage.getItem(UserService.SESSION_STORAGE_KEY);
        if (!token) {
            throw new Error("no token set , authentication required");
        }
        return sessionStorage.getItem(UserService.SESSION_STORAGE_KEY);
    }
    
    public signIn(): void {
        this.googleAuth.getAuth()
            .subscribe((auth) => {
                auth.signIn().then(res => this.signInSuccessHandler(res));
            });
    }
    
    private signInSuccessHandler(res: GoogleUser) {
            this.user = res;
            sessionStorage.setItem(
                UserService.SESSION_STORAGE_KEY, res.getAuthResponse().access_token
            );
        }
}

Lets go step by step through the example

  1. We create a angular Injectable() "service"
  2. The static property SESSION_STORAGE_KEY is just a sugar to store string in a property rather then hardcode
  3. in the constructor we inject the GoogleAuthService and making it a private property of our User class
  4. no we have 2 public methods , sign in and get token. The signIn should be used at user login page , it will open the google auth popup.
  5. The get token method is used for http request to google resource where a authentication is required.

Batch requests

From gapi docs https://developers.google.com/api-client-library/javascript/features/batch we should use gapi.client.newBatch()

But in our case we have typings and OOP, so we can do this:

export class FooService {
    constructor(gapiService: GoogleApiService) {
        gapiService.onLoad().subscribe(()=> {
           const myBatch: HttpBatch = new HttpBatch();
           myBatch.add(
               // your request
           );
        });
    }
}

Configurations

The GoogleApiConfig class provides the required configuration for the Api

Configuration is easy to use. The GoogleApiModule has a static method which sets the configs. As shown in the example you simply provide a configuration object of type ClientConfig.

 {
   client_id: "your client id",
   discoveryDocs: ["url to discovery docs", "another url"],
   scope: "space separated scopes"
}

Configure them according your google app configurations and resource scope.

Promotion

We are providing Web Development and Consulting Services. codeforges.com

ng-gapi's People

Contributors

bf-janderson avatar hakimio avatar jonzlotnik avatar lalogrosz avatar mohammadmusaei avatar rubencodeforges avatar vjuliani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-gapi's Issues

gapi.client doesn't exist

I've provide confing below

let gapiClientConfig: NgGapiClientConfig = {
  client_id: "******",
  discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"],
  scope: [
    "https://www.googleapis.com/auth/calendar"
  ].join(" ")
};

authorization works, then I need to use gapi.client.calendar , but .client doesn't exist
gapiService.onLoad().subscribe(() => {
// try achive gapi.client here
})

One more question - do we need provide API_key? I don't see any mention of this in library's documentaion, but this requirement exist in google calendar doc example

this.googleApi.onLoad(...).mergeMap is not a function

This is the log of the error I receive.

HomeComponent.html:2 ERROR TypeError: this.googleApi.onLoad(...).mergeMap is not a function
    at GoogleAuthService.push../node_modules/ng-gapi/lib/GoogleAuthService.js.GoogleAuthService.getAuth (GoogleAuthService.js:18)
    at GoogleSignInService.push../src/app/shared/google-sign-in.service.ts.GoogleSignInService.signIn (google-sign-in.service.ts:36)
    at HomeComponent.push../src/app/home/home.component.ts.HomeComponent.signIn (home.component.ts:26)
    at Object.eval [as handleEvent] (HomeComponent.html:2)
    at handleEvent (core.js:10258)
    at callWithDebugContext (core.js:11351)
    at Object.debugHandleEvent [as handleEvent] (core.js:11054)
    at dispatchEvent (core.js:7717)
    at core.js:8161
    at HTMLAnchorElement.<anonymous> (platform-browser.js:995)

The error seems to be coming from Here

GoogleAuthService.prototype.getAuth = function () {
        var _this = this;
        if (!this.GoogleAuth) {
            return this.googleApi.onLoad().mergeMap(function () { return _this.loadGapiAuth(); });
        }
        return Observable.of(this.GoogleAuth);
    };

Additions and Enhancements

Hello guys , first for all thanks for using the lib and supporting me by staring it.

With that issue i would like to gather some proposals for addition and enhancements for that lib.
Please fill free to comment here what you would like to see in the lib.
Thanks.

Errors using Angular CLI

While trying to use your Module in a project created using Angular CLI I faced some Errors. They may be caused by something I recognized in earlier projects using the CLI. In some cases CLI is not able to bundle the application code correctly when you are exporting more than one class/interface/component from a single file. In my case I got the following error when trying to run the application (not while packaging/building it):

Error: No provider for GoogleApiService!

I think the reason is, that you export GoogleApiService and NG_GAPI_CONFIG from one file.
Could you please verify that your module works with recent CLI projects, because I'd love to use it in my projects?

Thanks a lot!

Configuring gapi.auth2.ClientConfig

Hi Ruben(@rubenCodeforges),

First off, thanks for all of your work on this package.

I'm working on an app that is based on your reporting example.

Currently, the app works well, and I am able to sign in the user with their Google account. However, I would like for the oAuth dialog box to be redirected to (at Sign In), instead of popping up in a new tab.

I noticed that in the JS client library, Google mentions the gapi.auth2.ClientConfig interface for configuring parameters for gapi.auth2.init. Inside of this interface, I noticed ux_mode allows you to set the dialog box to either popup or redirect mode.

I tried adding ux_mode and redirect_uri settings into different parts of the app, but wasn't quite sure where to add these settings in, with regards to ng-gapi. Do you know if gapi.auth2.ClientConfig is able to be configured with ng-gapi, so that on sign in, the user is redirected to the oauth dialog box?

Any help is greatly appreciated.

Thanks for your time.

Sincerely,

Blaine H.

Working example?

Looks really great. Would you be able to provide a simple working example?

FWIW, I'm using the Reporting API,

const DISCOVERY_DOCS: string[] = [
  'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4',
];
const SCOPE: string = [
  'https://www.googleapis.com/auth/analytics',
  'https://www.googleapis.com/auth/analytics.readonly',
].join(' ');

They have a simple quickstart example here, but any API use would be good.

Using Google email api for sending emails.

Hi,
This repository seems very helpful to me, just I had a question for you guys.
Can we use this ng-gapi package, for sending system generated emails via web app?
If yes, then please tell me how to implement it. (A basic KT would also do)
Hope to hear from you guys soon.

Thanks in advance.

Broken for Angular 6 (RxJS 6)

After updating to Angular 6 which ships with RxJs 6, ng-gapi is not working any more due to RxJs 6 changes:

ERROR in node_modules/ng-gapi/lib/GoogleApiService.d.ts(1,10): error TS2305: Module '"path-to-project/node_modules/rxjs/Observable"' has no exported member 'Observable'.
[1] node_modules/ng-gapi/lib/GoogleAuthService.d.ts(2,10): error TS2305: Module '"path-to-project/node_modules/rxjs/Observable"' has no exported member 'Observable'.
[1] node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.

in file GoogleApiService.d.ts at line 1:
import { Observable } from "rxjs/Observable";

should become:
import { Observable } from "rxjs";

This would then not work anymore on projects using Rxjs below version 6. Is there any plan to update the library or creating new version of it?

Connect to Google App Engine Endpoints

Hi men!

First of all, thanks for this awesome Gapi service.

I need to consume some GAE (Google App Engine) functions. I deployed my backend into Google project, but I don't know how to connect it.

This is my simple example (without security or any checks):

@Api(name = "example", version = "v1", description = "API Endpoint")

public class MiApi {


	@ApiMethod(name = "hello", path = "hello", httpMethod = HttpMethod.POST)

	public Mensaje hello(@Named("n") String name) {
		return new Mensaje();
	}
}

How can I call this API mehod from Angular with ng-gapi?

Thanks!

Multi scripts added

Why not to check if script is already exists in head before adding new one

Manage session when token expired

Hi men!

I've a problem when the user session expires, also I can't call endpoint functions with this token.

What is the best way to handle it?

Insufficient Documentation

Hey there. I am looking to use this wrapper for my project. The documentation does not sufficiently describe how to use ng-gapi. there's also mention of examples which would be invaluable. Will you please update the README with comprehensive instructions?

How do we call a google API (like Calendar API)

Hi Ruben,

I'm a bit lost, I don't find the correct way to call an API like the Google Calendar API.

Do you have an exemple of implementation of the class bellow with gapi object ?

I know that I have to initialize the apiKey, do I need to use the gapi.client.init ?

export class FooService {
    constructor(gapiService: GoogleApiService) {
        gapiService.onLoad().subscribe(()=> {
           // Here we can use gapi
           // Do I need to use the gapi.client.init ? 
           // 
        });
    }
}

thanks

Kévin

Error: Property 'newBatch' does not exist on type 'typeof client'

Hi Ruben,
I have another problem . Let me explain details below....
I am trying to make batch requests rather than making separate requests (100 requests at a time) according to this doc: https://developers.google.com/api-client-library/javascript/features/batch

When I wrote this script , i got an error:
let batch = gapi.client.newBatch();
Error:
error TS2339: Property 'newBatch' does not exist on type 'typeof client'

So my question is how can I use gapi.client based on your lib?
Is there any special way to import/init/load gapi.client?
Thanks in advance.

How do we use this module?

As I see there used to be an example file which has been removed due to breaking changes.

The only hint we get right now is:

// Here we can use gapi

any further instructions on how we could actually use it?

How can I integrate google drive picker with ng-gapi?

Hello again!

Now I'm trying integrate your "ng-gapi library" with google-drive-picker. All of examples that I've founded are about AngularJS or simple JavaScript.

Is it possible to integrate google drive picker with ng-gapi?
How can I load google-drive-picker?

Failed to compile

Following your example, I have

NgModule({
  ...
  imports: [
    ...
    GoogleApiModule.setConfig(
      new GoogleApiConfig(
        CLIENT_ID, DISCOVERY_DOCS, SCOPE
      )
    ),
  ],
  ...
})
export class AppModule { }

But when running ng serve I get an error from Webpack:

ERROR in Error encountered resolving symbol values statically. Calling function 'GoogleApiModule', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in ...

And in the browser console I get this error:

Uncaught Error: Can't resolve all parameters for factory: ([object Object], ?).
    at syntaxError (http://localhost:4200/vendor.bundle.js:36507:34)
    at CompileMetadataResolver._getDependenciesMetadata (http://localhost:4200/vendor.bundle.js:49844:35)
    at CompileMetadataResolver._getFactoryMetadata (http://localhost:4200/vendor.bundle.js:49724:51)
    at CompileMetadataResolver.getProviderMetadata (http://localhost:4200/vendor.bundle.js:49996:43)
    at http://localhost:4200/vendor.bundle.js:49917:49
    at Array.forEach (native)
    at CompileMetadataResolver._getProvidersMetadata (http://localhost:4200/vendor.bundle.js:49878:19)
    at http://localhost:4200/vendor.bundle.js:49453:63
    at Array.forEach (native)
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:4200/vendor.bundle.js:49444:49)

Error en la compilacion

ERROR in /home/junior/proyectos/A_proyecto-emiteme/emiteme-frontend/node_modules/@types/gapi/index.d.ts (243,37): ',' expected.

No provider for InjectionToken ng-gapi.config!

Hey Ruben

I'm getting the error above when executing a unit test using angular-cli with jasmine/karma.
The test in particular is trying to instantiate the service into which I inject the GoogleApiService.

I have configured the appropriate module as per your readme example.

thanks in advance

Need sample code for how to grantOfflineAccess

Hi @rubenCodeforges ,

First of thank you for the awesome library.

I need to sync google calendar offline without logging in every time. For that i used, grantOfflineAccess() method. It responded code="some string" . with that how to get calendar list.

Can you please help me out in this. i am very newbie.

Google drive ?

Is possible to use for access and publish on Google Drive ?

Thx

Access Token expires~

Hi thanks for the great lib,
I was able to implement google authentication using this lib but Access tokens typically expire after 60 minutes.
Is there a way to refresh token so I can get a new (valid) access token?

Any help would be appreciated!
Thanks

Feature: change platform.js to api.js

Hi. Why are you using the platform.js library (apis.google.com/js/platform.js) instead of api.js (apis.google.com/js/api.js)? Correct me if i'm wrong but platform.js is for the Google+ JavaScript API, no?

Option to lazy load Gapi

Right now the moment you inject GoogleApiService it'll load the gApi, I'd much rather have the option to wait until I want to use the api to determine if I load it or not. In order to work around this I have to use an injector in the service I want to use the api from.

GoogleUser reference?

In your GoogleAuthService example, where are you getting the Interface for GoogleUser?

Thanks

Login fails with error > err = {error: "popup_closed_by_user"}

After setting up and running with my own client id I go through the login process and select the needed google account in the popup.

Once this has been selected the login fails with the error in the console being:

err = {error: "popup_closed_by_user"}

from line 34 of UserService.ts which uses the error handler for signin

Any idea how to fix this?

Auth popUp is not open when calling this.googleAuth.getAuth()

here is the package.json just in case is an issue with some versions

{
"name": "egret",
"version": "6.0.0",
"license": "https://themeforest.net/licenses/terms/regular",
"scripts": {
"ng": "ng",
"start": "ng serve",
"serveProd": "ng serve --environment=prod",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "5.2.0",
"@angular/cdk": "5.2.0",
"@angular/common": "5.2.0",
"@angular/compiler": "5.2.0",
"@angular/core": "5.2.0",
"@angular/flex-layout": "2.0.0-beta.10",
"@angular/forms": "5.2.0",
"@angular/http": "5.2.0",
"@angular/material": "5.2.0",
"@angular/platform-browser": "5.2.0",
"@angular/platform-browser-dynamic": "5.2.0",
"@angular/router": "5.2.0",
"@swimlane/ngx-datatable": "11.1.7",
"angular-tag-cloud-module": "^3.0.0",
"angularfire2": "^5.0.0-rc.11",
"angularx-social-login": "^1.1.8",
"chart.js": "2.5.0",
"classlist.js": "1.1.20150312",
"core-js": "2.4.1",
"date-fns": "1.28.5",
"firebase": "^5.3.0",
"hammerjs": "2.0.8",
"ng-gapi": "0.0.51",
"ng2-charts": "1.6.0",
"ng2-file-upload": "1.2.1",
"ng2-translate": "5.0.0",
"ng2-validation": "4.2.0",
"ngx-webstorage": "^2.0.1",
"perfect-scrollbar": "1.3.0",
"recordrtc": "^5.4.6",
"rxjs": "^6.2.2",
"rxjs-compat": "^6.2.2",
"wavesurfer.js": "^2.0.5",
"web-animations-js": "2.3.1",
"zone.js": "0.8.20"
},
"devDependencies": {
"@angular-devkit/core": "0.3.1",
"@angular/cli": "^1.6.8",
"@angular/compiler-cli": "5.2.0",
"@angular/language-service": "5.2.0",
"copy-webpack-plugin": "4.3.0",
"@types/hopscotch": "0.2.28",
"@types/jasmine": "2.5.38",
"@types/node": "6.0.60",
"codelyzer": "~2.0.0",
"enhanced-resolve": "3.3.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "~0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "~0.2.2",
"protractor": "~5.1.0",
"ts-node": "2.0.0",
"tslint": "4.5.0",
"typescript": "2.4.2"
}
}

and here is the code in the user.service.js

public getToken(): string {
    const token: string = sessionStorage.getItem(UserService.SESSION_STORAGE_KEY);
    if (!token) {
      throw new Error('no token set , authentication required');
    }
    return sessionStorage.getItem(UserService.SESSION_STORAGE_KEY);
  }

  public signIn(): void {
    this.googleAuth.getAuth()
      .subscribe((auth) => {
        auth.signIn().then(res => this.signInSuccessHandler(res));
      });
  }

  private signInSuccessHandler(res: GoogleUser) {
    this.user = res;
    sessionStorage.setItem(
      UserService.SESSION_STORAGE_KEY, res.getAuthResponse().access_token
    );
  }

when i call the signIn() method from the component the auth popup window never shows up. The browser is not blocking the popup the method isn't doing anything

If you need any other info just ask.

Thanks

Issue in production mode

Hello.

I'm starting using your lib in my project. And everything is working fine once in dev mode (ng serve) but when it goes to production (ng build -prod) I get the error:

ERROR TypeError: Cannot read property 'clientId' of undefined

Raised from minified version of

function GoogleApiConfig(configs) {
        this.CLIENT_ID = configs.clientId;
        this.DISCOVERY_DOCS = configs.discoveryDocs;
        this.SCOPE = configs.scope;
    }
My Implementation:
@NgModule({
  imports: [
    CommonModule,
    AuthRoutingModule,
    FormsModule,
    GoogleApiModule.setConfig({
      clientId: environment.socialAuth.google.clientId,
      discoveryDocs: [''],
      scope: ""
    })
  ],
...
})

After refresh, first signout fails, second succeeds

After refresh the signOut() method fails.

Description

After I login in my application I'm redirected to the dashboard. If I immediately logout, it works fine. But if I refresh the page and then logout, it throws the following error:

Error: nb
at Object._.tE (cb=gapi.loaded_0:175)
at jF. (cb=gapi.loaded_0:213)
at new _.C (cb=gapi.loaded_0:104)
at jF.BT (cb=gapi.loaded_0:213)
at SafeSubscriber._next (authentication.service.ts:49)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at GoogleAuthService.js:24

But, if I click again it will sing me out with no problems. I obviously don't want the user to click twice or this error to appear...

Expected Behavior

It should signout without errors at any stage of the application navigation.

Actual Behavior

If navigated (or refreshed) throws an error, and second time I click then it signs out perfectly.

Uncaught TypeError: gapi.client.HttpBatch is not a constructor

Readme describes a way to work with HttpBatch like this:

export class FooService {
    constructor(gapiService: GoogleApiService) {
        gapiService.onLoad().subscribe(()=> {
           const myBatch: HttpBatch = new HttpBatch();
           myBatch.add(
               // your request
           );
        });
    }
}

But for me it's unclear where HttpBatch reference come from.


If use alias:

import HttpBatch = gapi.client.HttpBatch;

// ...

const batch: HttpBatch = new HttpBatch();

I got

Uncaught ReferenceError: gapi is not defined

If use full path:

const batch: gapi.client.HttpBatch = new gapi.client.HttpBatch();

I got

Uncaught TypeError: gapi.client.HttpBatch is not a constructor


Sure, it all happens even inside of gapiService.onLoad() subscribe callback.

How can this problem be solved?

Thanks in advance!

Angular Cli prod build warning

Can't resolve all parameters for GoogleApiService in ../node_modules/ng-gapi/lib/GoogleApiService.d.ts: (?). This will become an error in Angular v5.x

Token session expired

Hi!!!

Is it possible to declare a listener that trigger 'something' when session's token expired?

Thanks anyway!

Retrieve CurrentUser after refresh of the browser

Hello,

I would like to know how can I restore the GoogleUser after a refresh of the page?
I still have the token in the session but the GoogleUser is set as Undefine after "F5"
Is there a method to call the GAPI to retrieve the currentUser session?

Thanks.

Not working with SystemJS

When using in a project with SystemJS got the following error:

Error: Unable to dynamically transpile ES module
A loader plugin needs to be configured via SystemJS.config({ transpiler: 'transpiler-module' }).
Instantiating http://localhost:3010/node_modules/ng-gapi/lib/index.js
Loading http://localhost:3010/app/app.module.js
Loading app
at transpile (instantiate.js:467)
at instantiate.js:245
at ZoneDelegate.invoke (zone.js:392)
at Zone.run (zone.js:142)
at zone.js:873
at ZoneDelegate.invokeTask (zone.js:425)
at Zone.runTask (zone.js:192)
at drainMicroTaskQueue (zone.js:602)
at

The parts of systemjs.config.ts

map : {
...
'ng-gapi': 'node_modules/ng-gapi/lib'
}

packages: {
...
'ng-gapi': {
main: 'index.js',
defaultExtension: 'js'
}

app.module

...
import { GoogleApiModule, NG_GAPI_CONFIG } from 'ng-gapi';
...
export interface NgGapiClientConfig extends ClientConfig {
discoveryDocs: string[];
}
...

@NgModule({
imports: [
...
GoogleApiModule.forRoot({
provide: NG_GAPI_CONFIG,
useValue: gapiClientConfig
}),
...

Google Auth is being blocked by browser

Hello, I was able to get the ng-gapi to work however, I'm experiencing a slight technical issue, whenever I perform a sign in with google(.eg calling the googleAuthService.getAuth()) The auth pop up is being blocked. Is there by any chance where instead of a pop it will redirect to the auth page instead of popping up?

Change detection after auth iframe

after auth iframe appears - component loses control of change detection.
Changes can be applied only through changeDetector

I use NgRx so my code for authorization is next (NgRx Effects):

@Effect()
tryLogin = this.actions$
  .ofType(AuthActionTypes.TRY_LOGIN)
  .switchMap(() => this.signIn())
  .switchMap(result => of(result ? new LoginSuccess() : new LoginFailure()))

@Effect()
loginSuccess = this.actions$
  .ofType(AuthActionTypes.LOGIN_SUCCESS)
  .switchMap((): Observable<RouterActionType> => of(new RouterActions.Go({path: ['/calendar']})))

private signIn(): Observable<boolean> {
  return this.googleAuth.getAuth()
    .switchMap(auth => {
      return fromPromise(auth.signIn())
    })
    .map((res: GoogleUser) => {
      this.signInSuccessHandler(res)
      return true
    })
    .catch( (err) => {
      console.error('ERROR: ', err);
      return of(false)
    })
}

private signInSuccessHandler(res: GoogleUser) {
  this.user = res;
  sessionStorage.setItem(
    this.SESSION_STORAGE_KEY, res.getAuthResponse().access_token
  );
}

How sholuld I use library to avoid this behavior, thanks!

ServerSide Auth - Sign JSON Key and Get Access Token?

I'm trying to use server side Authorization for the google analytics embed API https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

The example they give for the python gapi client is as follows:
service-account.py

from oauth2client.service_account import ServiceAccountCredentials

The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'

Defines a method to get an access token from the ServiceAccount object.

def get_access_token():
  return ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILEPATH, SCOPE).get_access_token().access_token

would that be possible with ng-gapi? how so?

Thank you!

Err, no token set authentication required.

Hi, I'm very new to programming angular2. When I tried using your example code, i get this error when calling getToken(), which would mean there is either no token or the token is wrong? When I check the session storage, there is a token there but I can' seem to get it using getToken()? Did I miss out something?

    public signIn() {
        this.googleAuthService.getAuth().subscribe((auth) => {
            auth.signIn().then(res => this.signInSuccessHandler(res), err => this.signInErrorHandler(err));
            console.log(auth)
        });
    }
    public isUserSignedIn(): boolean {
        return !_.isEmpty(sessionStorage.getItem(UserGapiService.SESSION_STORAGE_KEY));
    }

    private signInSuccessHandler(res: GoogleUser) {
        this.ngZone.run(() => {
            this.user = res;
            sessionStorage.setItem(
                UserGapiService.SESSION_STORAGE_KEY, res.getAuthResponse().access_token
            );
        });
    }

    public getToken(): string {
        this.token = sessionStorage.getItem(UserGapiService.SESSION_STORAGE_KEY);
        console.log(this.token)
        if (!this.token) {
            throw new Error("no token set , authentication required");
        }
        return sessionStorage.getItem(UserGapiService.SESSION_STORAGE_KEY);
    }

New ng-dynamic-forms module in developmen

Hey everyone i wanted to point out that im making a new probably useful module for Angular.

ng-dynamic-form

Should help reduce repeatable tasks when building forms.
The goal is not only make dynamic forms easy to build but even make the process more automated.
Imagine a situation when you have new user form you have a backend enpoint and some interface describing the fields, now the idea is to feed the interface ( better class ) to the ng-dynamic-form and it should build the whole new user form for you.

For now feel free to fork and modify at you will , later ill be publishing it as a npm lib. Need some work to finish first

popup_blocked_by_browser on first attempt to sign in

I am calling the service directly from template yet still getting popup_blocked_by_browser error on first try to log in.

What my service method looks like:

public signIn(): void {
        this.googleAuth.getAuth()
            .subscribe((auth) => {
                auth.signIn().then(res => this.signInSuccessHandler(res));
            });
    }

This is what my html looks like:

<div class='navbar-fixed'>
  <nav class="white" role="navigation">
      <div class="nav-background">
          <div class="pattern active" style="background-image: url('http://placehold.it/1400x300');"></div>
      </div>
      <div class="nav-wrapper container">
        <a id="logo-container" href="#" class="brand-logo hide-on-small-only">Private Lessons Hub</a>
        <ul class="right">
          <li [hidden]="!profile">
            <a  
                materialize="dropdown"
                id='profilePicLink'
                class="dropdown-button" 
                href="javascript:void(0)" 
                data-activates="userDropdown">
              <img *ngIf="profile" id='profilePic' src="{{profile.imageUrl}}"  class="circle responsive-img">
              <i class="material-icons right">arrow_drop_down</i>
            </a>
          </li>
          <li *ngIf='!profile'>
            <a class="waves-effect waves-light tooltipped" class="tooltipped" materialize="tooltip" data-position='bottom' data-delay="50" data-tooltip="Log in with google credentials" (click)='gapiService.signIn()'>Log In</a>
          </li>
        </ul>
      </div>

  </nav>
</div>

Client apis not loaded

Hello,
I might be totally wrong, but I can't get GoogleApiService working. Authentication is ok. I have correct configuration. Still, when I step into gapiService.onLoad callback based on your usage pattern, there is no gapi.client, even less gapi.client.drive defined in window object.
I have a non-ng JavaScript version, that works...

How to proceed? Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.