Google Login на Angular - гэппи не определена ошибка - PullRequest
0 голосов
/ 23 октября 2018

Я реализовал Google Login на Angular 5, который работает при первом входе в систему, но когда пользователь уже вошел в систему и вернулся на сайт, он получает ошибку gapi is not defined в консоли Chrome.Я почти уверен, что это как-то связано с областью действия Angular, поскольку у меня есть переменная gapi, объявленная в модуле входа в систему, как показано здесь:

import { Component, OnInit } from '@angular/core';
import { WmApiService } from '../wm-api.service';
import { Router } from "@angular/router";

declare const gapi: any;

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

  constructor(private _wmapi: WmApiService, private router: Router) { }

  public auth2: any;
  userProfile: any;
  user: any;

  // Initalise Google Sign-On
  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: '[clientid].apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }

  // Log user in via Google OAuth 2
  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (googleUser) => {
        // Get profile from Google
        let profile = googleUser.getBasicProfile();        
        // Save user to the API until changed
        this._wmapi.tempuser = profile.getName().match(/\(([^)]+)\)/)[1];
        this._wmapi.tempuseravatar = profile.getImageUrl();
        this._wmapi.tempuserfullname = profile.getName();
        this._wmapi.tempuseremail = profile.getEmail();
        // Log the user in
        this._wmapi.userloggedin = 1;
        // Redirect to dashboard
        this.router.navigate(['/dashboard']);
      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
        // To get auth token - googleUser.getAuthResponse().id_token;
        // To get user id - profile.getId();
      });
  }

  ngAfterViewInit(){
    this.googleInit();
  }

  ngOnInit() {
  }

}

Я убедился, что получилgoogle api-скрипт в index.html, поэтому я не уверен, как мне понять, что пользователь вошел в систему, и не выкинуть пользователя обратно на страницу входа, когда я перехожу к панели инструментов, например?

...