我正在尝试使用 Google Identity Services 库在 Angular(+Express) 应用程序中实现 Google Auth。在我看来,我已经按照谷歌教程完成了所有事情。但是出现了“[ERROR] TS2304: Cannot find name 'google'”。
我已将
<script src="https://accounts.google.com/gsi/client" async defer></script>
添加到index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Render</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
<script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
并尝试
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { BehaviorSubject, Observable, catchError, tap } from 'rxjs';
import { User } from '../_interfaces/user';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:4200',
}),
};
@Injectable({
providedIn: 'root',
})
export class AuthService {
private userSubject = new BehaviorSubject<User | null>(this.getData);
loggedInUser: Observable<User | null>; //
client: any;
access_token: any;
constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object) {
this.loggedInUser = this.userSubject.asObservable();
this.init();
}
init() {
this.client = google.accounts.oauth2.initTokenClient({
client_id: '***********',
scope: 'https://www.googleapis.com/auth/calendar.readonly \
https://www.googleapis.com/auth/contacts.readonly',
callback: (tokenResponse: { access_token: any }) => {
this.access_token = tokenResponse.access_token;
},
});
}
但有:[错误] TS2304:找不到名称“google”。 [插件角度编译器]
你能帮我吗?
当 Typescript 无法识别 Google 身份服务库的类型定义时,会出现此错误。您可以按照以下步骤来解决这个问题。
compilerOptions
文件的tsconfig.json
的类型数组是否包含类型google.identity.oauth2
。tsconfig.json
文件
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"types": ["google.identity.oauth2"]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
npm install --save-dev @types/google.identity.oauth2