首页 > 解决方案 > Google 登录按钮未出现在 Angular 中

问题描述

我正在尝试在我的 Angular 应用程序中添加 google 登录按钮,但它没有出现。它的高度总是 0,如果我改变它 - 没有按钮出现。我该如何处理?我以为可能是样式问题,但我错了。我试图在 SO 中找到答案,但没有找到任何合适的解决方案。我是 Angular 的新手,需要一些帮助。

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="google-signin-client_id" content="MY_ID">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body class="mat-typography">
  <app-root></app-root>
</body>
</html>

我的 login.component.ts 看起来像这样:

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

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

    constructor() { }

    onSignIn(googleUser: any) {
        console.log(googleUser);
        var profile = googleUser.getBasicProfile();
        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.
    }

    ngOnInit(): void {
    }

}

和 login.component.html

<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">

    <mat-card class="box">
        <mat-card-header>
            <mat-card-title>Sign in</mat-card-title>
        </mat-card-header>

        <form class="login-form">
            <mat-card-content>
                <mat-form-field class="login-form_full-width">
                    <input matInput placeholder="Username">
                </mat-form-field>

                <mat-form-field class="login-form_full-width">
                    <input matInput placeholder="Password">
                </mat-form-field>
            </mat-card-content>
            <button mat-stroked-button color="accent" class="btn-block">Log in</button>
        </form>
        <div class="g-singin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    </mat-card>

</div>

我究竟做错了什么?

标签: javascripthtmlangular

解决方案


我猜你缺少初始化 gapi 模块,像这样:

gapi.load('auth2', function(){
    gapi.auth2.init();
});

如果您仍然遇到问题,请考虑使用为 angular 制作的 npm 模块: https ://www.npmjs.com/package/angularx-social-login


推荐阅读