Utilizing data-onsuccess for authenticating Google sign in within an Angular environment

I am currently working on implementing a sign-in feature using Google Sign-In for Websites. The sign-in button is displayed in my application, the login process works as expected but the onSignIn(googleUser) method is not getting called. I believe I need to somehow bind the button in my component file and link it to the callback function, but I have yet to figure out how to achieve this with Angular 5.

How can I trigger the callback on (data-onsuccess) when the login is successful and pass the retrieved user data to onSignIn(googleUser) in Register.component.ts?

register.component.ts

import {Component} from '@angular/core';
import {RegisterService} from './register.service';

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

  constructor(private registerService: RegisterService) {

  }

  onSignIn(googleUser) {
    this.registerService.googleSignIn(googleUser);
  }
}

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
  <meta name="google-signin-client_id" content="obfuscated for Stack Overflow">
  <title>Thee</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

register.component.html

<div class="g-signin2" (data-onsuccess)="onSignIn()"></div>

Any assistance would be greatly appreciated. Thank you.

Answer №1

Include this code snippet in your component.ts file

declare const gapi: any;
ngOnInit() {
this.initializeGoogle();}
public auth2: any;


public initializeGoogle() {
let that = this;
gapi.load('auth2', function () {
  that.auth2 = gapi.auth2.init({
    client_id: "YOUR_CLIENT_ID.apps.googleusercontent.com",
    cookiepolicy: 'single_host_origin',
  });
  that.onSignIn(that.element.nativeElement.firstChild);
}); }
onSignIn(element) {
console.log('element is now ', element);

this.auth2.attachClickHandler(element, {},
  function (googleUser) {

var profile = googleUser.getBasicProfile();
const desc = {
  'ID: ' : profile.getId(),
  'Name: ' : profile.getName(),
  // 'Image URL: ' : profile.getImageUrl(),
  'Email: ' : profile.getEmail()
}
alert(JSON.stringify(desc));
// console.log('Token || ' + googleUser.getAuthResponse().id_token);
console.log(profile)
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.})};}

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

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Get the HeatMap ngx swimlane chart as an image by downloading or exporting it

Is there a way to download or export the HeatMap ngx swimlane chart as an image? If you need a solution for downloading the chart as an image, please refer to this Plunker URL: https://plnkr.co/edit/2rtX5cueg2hlzmztUbkH?p=preview I am looking for any opt ...

Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes. The final code structure should resemble the following: @Injectable() class MyService { constructor(private injector ...

Apologies, but your payment request was not successful. Please try using an alternative payment method or reach out to us for assistance. Find out more information about error code [OR

While trying to test Google Pay using a fake card, I encountered an error message stating: Your request failed. Use a different payment method, or contact us. Learn more [OR-CCSEH-21]. Below is the Angular code snippet that I am working with: paymentReques ...

Can a default arrow function be exported in TypeScript using only one line?

const myFunction: () => void = () => { console.log('I am able to export my function like this'); }; export default myFunction; export default () => void = () => { console.log('I am unable to export my function like thi ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Having trouble accessing the database in Angular and Ionic through a provider on a Tabbed page

I created a Home page with tabs using Ionic 3 and Angular. The tabs are named Stats and Calc. When clicking on the Stats tab, it triggers the class/component stats.ts (displayed below). This component utilizes two providers: CropProvider and ContractProvi ...

Stop useEffect from triggering during the first render

I'm working on implementing a debounce functionality for a custom input, but I'm facing an issue where the useEffect hook is triggered during the initial render. import { useDebouncedCallback } from "use-debounce"; interface myInputProps { ge ...

Error: Cannot access the 'people' property as it is undefined

Can anyone assist me with troubleshooting an issue I'm having while trying to set up a Google People API authentication service in Angular? I keep encountering the following error in the Chrome console: Uncaught (in promise): TypeError: Cannot read ...

Challenges in routing from AngularJS to Angular 2

When using AngularJS, if there are two pages (home.html and away.html) serving as application modules in an enterprise, routes can be created independently for each page. For example, the home page can have routes for bedroom, chamber, hall, etc., while th ...

Angular2 Uniqueness Validator: Ensuring Data Integrity

Within my Angular2 form field, I am trying to ensure that the inputted value does not already exist. The challenge lies in accessing instance members within my custom validator function, codeUnique(). Upon execution, "this" refers to either FormControl o ...

Guide on combining two classes as the base class for an extended class in Typescript

Is it possible to create a higher order function (HOF) that modifies or adds a property to the prototype of a given class? interface IStore { new (): {}; } interface IWatchable { new() : { watch: boolean; }; } const Store = <T extends ISt ...

Locate individual user according to specified criteria

I'm currently working on implementing a sign-in feature for the website I'm developing. However, I am facing issues with retrieving a user based on their login credentials, as my search results always return null. Below is an excerpt from my use ...

Paper-dropdown-menu component failing to render properly in web browser

Encountering an issue with the rendered HTML for a basic paper-dropdown-menu. Instead of displaying as a styled menu, the list items are just appearing as a plain list on the page. Upon clicking the rendered paper-input component within the dropdown, the ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

What is the best method for setting up a worldwide list of approved URLs?

Looking to incorporate a universal whitelist feature for secure URLs in bypassing resource URLs within Angular 2, inspired by the functionality offered in AngularJS via the $sceDelegateProvider as explained here I've attempted to consult the Angular ...

Apply a border to the div that has been selected

I have a tool for storing information and I am using *ngFor to display each instance in a line. Is there a way to add a border when clicking on a line? The border should only appear on the clicked line, disappearing from the previous one if another line i ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

What is the best way to wait for a thread to finish executing before calling a function in Angular 5?

After starting a thread, I've encountered an issue where a function is being called before the thread has completed. What changes should I make to ensure the function is called after the thread completes? this._listService.getListById ...

Master Checkbox in HTML Table Not Functioning for Selecting/Deselecting All Items

https://i.sstatic.net/RKWaC.png I'm facing an issue with my code that allows me to select and deselect multiple rows in a table. Specifically, I'm struggling with implementing a SELECTALL/DESELECTALL feature using a master checkbox. You can vie ...