How to implement SignIn with Google in Angular 2 using Typescript

前端 未结 7 979
梦毁少年i
梦毁少年i 2020-11-28 04:11

I have been trying to implement sign in with Google in angular 2 in a separate login component. I am unable to implement it with the documentation available in Google https:

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:49

    src/index.html

    In the index.html file of your app you need to add this in the section:

    
    
    
    

    typings/browser/ambient/gapi/

    You need to add gapi & gapi.auth2 to your typings:

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

    (see this borysn's question to understand this a little better).

    src/app/+login/login.component.ts

    This is the file of my component, here you need to use the ngAfterViewInit() to use the gapi an get the auth. And you can follow the implementation here developers.google...sign-in/web/build-button

    As an example, this is my template:

    and sign in function:

    ngAfterViewInit() {
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 240,
            'height': 50,
            'longtitle': true,
            'theme': 'light',
            'onsuccess': param => this.onSignIn(param)
        });
    }
    
    public onSignIn(googleUser) {
        var user : User = new User();
    
        ((u, p) => {
            u.id            = p.getId();
            u.name          = p.getName();
            u.email         = p.getEmail();
            u.imageUrl      = p.getImageUrl();
            u.givenName     = p.getGivenName();
            u.familyName    = p.getFamilyName();
        })(user, googleUser.getBasicProfile());
    
        ((u, r) => {
            u.token         = r.id_token;
        })(user, googleUser.getAuthResponse());
    
        user.save();
        this.goHome();
    };
    

    UPDATE: After some time, and taking in consideration the comments, this answer needed a small update.

提交回复
热议问题