The Google Sign-in feature is unable to access the property 'load' due to being undefined

I'm currently working on implementing a Google Sign-in feature in an Angular application, but I'm encountering the following error:

Cannot read property 'load' of undefined

This was actually working perfectly just an hour ago, but now it seems to be experiencing a loading issue. I suspect that something is out of sync somewhere, but I'm unsure how to resolve it.

For clarification, my app doesn't load directly onto the login page from the start; instead, I navigate to it using the address bar in Chrome (not sure if this could be causing the problem). The client ID is correct, I've just replaced it for security purposes in this question.

login.component.ts

import { Component, OnInit } from '@angular/core';

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

export class LoginComponent implements OnInit {

  constructor() { }

  public auth2: any;
  user: string;
  gapi: any;

  public googleInit() {
    this.gapi.load('auth2', () => {
      this.auth2 = this.gapi.auth2.init({
        client_id: 'client_id.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }

  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (googleUser) => {

        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
        //YOUR CODE HERE
        this.user = "";

      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });
  }

  ngAfterViewInit(){
    this.googleInit();
  }

  ngOnInit() {
  }

}

login.component.html

<div id="googleBtn">Login w/ Google</div>

Answer №1

The gapi instance variable contains the load method, but it appears to be uninitialized. What would be the appropriate way to initialize this variable?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can dynamic values be sent to a custom form validator in Angular 6?

Essentially, I am facing a challenge with validating form inputs that are interdependent (for example, ensuring that the "from" time is earlier than the "to" time). However, I'm unsure of the best approach to tackle this issue. Below is my form group ...

What is the best way to assign a conditional value to this Angular attribute within my HTML code?

I'm currently developing a web application using Angular and PrimeNG. My question is whether it's possible to conditionally add a PrimeNG component attribute based on the value of a property. In my HTML file, I have the following code: <span [ ...

The navigate function fails to function properly in response to HttpClient

Hey there! I am facing an issue with the router.navigate function in Angular. When I try to use it within a subscribe method for httpClient, it doesn't seem to work as expected. Can someone please help me understand why this is happening and how I can ...

Tips for keeping an Angular Material Dialog component at the forefront of your application's layout

My application is designed with a vertical Navigation Bar positioned on the left side of the screen, and a Home Component displayed in the <router-outlet> to its right. However, I am facing an issue where when I open a Dialog Component within the H ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

Angular 2: Toggle multiple checkboxes with a single click

I am faced with a scenario where I have 5 checkboxes implemented as shown below <input type="checkbox" [checked]="chk1" (change)="chk1 = !chk1" />chk1 &nbsp; <input type="checkbox" [checked]="chk2" (change)="chk2 = !chk2" />chk2 &nbsp; ...

Steps for subscribing to an Observable in a Jasmine unit test

I am currently working on incorporating mock json data into my unit tests by creating a utility function for other test files to utilize. Here is an example of how it can be implemented: @Injectable({providedIn: 'root'}) export class MockUtilsSer ...

Querying with Node SQLite fails to return a value

So, here's my little dilemma: I have 3 methods that need to access a database file (SQLite3). export function F_SetupDatabase(_logger: any): void export function Q_RunQuery(query: string, db: "session" | "global"): any export func ...

Add a calendar icon to the DateRangePicker in React Mui

I am trying to set up a DateRangePicker using Material UI with a calendar icon. Here is an example of how I want it to look: https://i.stack.imgur.com/LnYnY.png After following the API documentation and using this code: components={{ OpenPickerIcon: Cal ...

The content displayed in the PrimeNG p-table is limited to only the table name with no additional information

After upgrading Angular to version 9, I switched from p-dataTable to p-table in PrimeNG. With a table named users, I intended to display them on the screen upon rendering the view using the following HTML: users = ['one','two','thr ...

Updating the value of a key in an object is not functioning as expected

There is a single object defined as requestObject: any = { "type": 'type1', "start": 0, "size": 10, "keywords": ['abcd','efgh'], filters: [], } Next, attempting to change the value for keyword, I updat ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

Developing an Angular 8 web application with seamless integration of ADFS 2.0 for

Looking for guidance on implementing authentication using ADFS 2.0 in my Angular 8 application. Any tips or sample applications would be greatly appreciated! ...

Download and store the response body using FileSaver and blob technology

I'm encountering an issue where I am trying to download and save a file from an API. The original filename is text.txt, but after saving, the file is named: _text.txt_. Additionally, the content of this saved file is displaying as: [object Object] Be ...

Enhancing supertest functionality with Typescript

Currently, I am working on extending the functionality of supertest. After referencing a solution from Extending SuperTest, I was able to implement the following example using javascript: const request = require('supertest'); const Test = reque ...

The Express API controller is unexpectedly receiving empty strings

I am encountering an issue where my API is receiving an empty string instead of the expected data when I send post requests with a single string in the body. Below are the client, server, and controller components involved: Function call (client): const ...

Creating a generic that generates an object with a string and type

Is there a way to ensure that MinObj functions correctly in creating objects with the structure { 'name': string }? type MinObj<Key extends string, Type> = { [a: Key]: Type } type x = MinObj<'name', string> Link to Playgr ...

Install NPM without changing directories to the folder

Currently, I am using Windows Powershell and a pipeline to create the package for an application deployment. Here is the pipeline setup: https://i.stack.imgur.com/am2iR.png My current obstacle revolves around the "npm install" command, as I want to avoid ...

Expanding a TypeScript type by creating an alias for a property

I am working on defining a type that allows its properties to be "aliased" with another name. type TTitle: string; type Data<SomethingHere> = { id: string, title: TTitle, owner: TPerson, } type ExtendedData = Data<{cardTitle: "title&qu ...

typescript ways to exclude enum values

I am working with enums in TypeScript. enum Status { Cancelled = 'cancelled', Completed = 'completed', Created = 'created' } Now, I need to create another enum that includes only the values Completed and Created. enum S ...