# @abacritt/angularx-social-login 中文文档

规范地址：https://npmcn.com/package/%40abacritt/angularx-social-login/

版本：2\.6\.0
npm 元数据更新时间：2026-03-28T11:50:59.884Z
中文译文更新时间：2026-11-05T17:27:51.580Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40abacritt/angularx-social-login
原文对照：https://npmcn.com/package/%40abacritt/angularx-social-login/?lang=original
项目主页：https://github.com/abacritt/angularx-social-login#readme
源码仓库：https://github.com/abacritt/angularx-social-login

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：155 kB，6 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@angular/common \>=21\.2\.6，@angular/core \>=21\.2\.6
- 首次发布：2022-04-15T07:18:26.167Z
- 最新版本发布：2026-03-28T11:50:59.745Z
- 近 30 天下载量：362236（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：23（近 12 个月 1 个）

## 中文简介

Angular 19 的社会登录和认证模块. 支持Google,Facebook,亚马逊和VK认证. 也可扩展到其他供应商.

## 安装

```sh
npm install @abacritt/angularx-social-login
```

也可以使用：`pnpm add @abacritt/angularx-social-login`、`yarn add @abacritt/angularx-social-login`、`bun add @abacritt/angularx-social-login`

## README

# 角社会登录

> 使用 [讨论情况](https://github.com/abacritt/angularx-social-login/discussions) 问讯.

Angular 21 的社会登录和认证模块. 支持认证 **谷歌**, (中文(简体) ), **脸书**, (中文(简体) ), **亚马逊**, (中文(简体) ), **微软**,以及 **VK 数字** 从盒子里出来。 可扩展至其他 也提供商.

看看这个 [演示](https://abacritt.github.io/angularx-social-login/)。 。 。 .

### 兼容性矩阵

| 库版本 | 角质版本 |
| --- | --- |
| @abacritt/angularx-social-login: 2.6 | 21国 |
| @abacritt/angularx-social-login:2.5.X (中文(简体) ) | 20国 |
| @abacritt/angularx-social-login:2.4.X (中文(简体) ) | 第 19 条 |
| @abacritt/angularx-social-login:2.3.X 互联网档案馆的存檔,存档日期2013-10-22 | 第 18 条 |
| @abacritt/angularx-social-login:2.2.X (中文(简体) ) | 页:1 |
| @abacritt/angularx-social-login:2.1.X (中文(简体) ) | 第16、17条 |
| @abacritt/angularx-social-login:2.0.X (中文(简体) ) | 第15、16条 |
| @abacritt/angularx-social-login:1 互联网档案馆的存檔,存档日期2014-10-02 | 第十三、十四、十五条 |
| angularx-social-login:4 (韩语) | 第12、13条 |
| angularx-social-login:3 (中文(简体) ) | 第9、10、11条 |
| angularx-social-login:2 (韩语) | 第5、6、7、8条 |

## 开始

### 通过 npm 安装

```sh
npm i @abacritt/angularx-social-login
```

### 导入模块

在你身边 `AppModule`,导入 `SocialLoginModule`

```javascript
import { SocialLoginModule, SocialAuthServiceConfig } from '@abacritt/angularx-social-login';
import {
  GoogleLoginProvider,
  FacebookLoginProvider
} from '@abacritt/angularx-social-login';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    SocialLoginModule
  ],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        lang: 'en',
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(
              'clientId'
            )
          },
          {
            id: FacebookLoginProvider.PROVIDER_ID,
            provider: new FacebookLoginProvider('clientId')
          }
        ],
        onError: (err) => {
          console.error(err);
        }
      } as SocialAuthServiceConfig,
    }
  ],
  bootstrap: [...]
})
export class AppModule { }
```

### 与 Facebook 签约

```javascript

import { SocialAuthService } from "@abacritt/angularx-social-login";
import { FacebookLoginProvider } from "@abacritt/angularx-social-login";

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

  constructor(private authService: SocialAuthService) { }

  signInWithFB(): void {
    this.authService.signIn(FacebookLoginProvider.PROVIDER_ID);
  }

  signOut(): void {
    this.authService.signOut();
  }

}
```

### 用 VK 签名

```javascript

import { SocialAuthService } from "@abacritt/angularx-social-login";
import { VKLoginProvider } from "@abacritt/angularx-social-login";

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

  constructor(private authService: SocialAuthService) { }

  signInWithVK(): void {
    // default usage without defining access level
    this.authService.signIn(VKLoginProvider.PROVIDER_ID);

    // define access level
    // https://dev.vk.com/reference/access-rights
    this.authService.signIn(VKLoginProvider.PROVIDER_ID, ['offline', 'email']);
  }

  signOut(): void {
    this.authService.signOut();
  }

}
```

### 与 Google 签名

`GoogleLoginProvider` 没有 `signIn()` 作为其他提供者,登录流程由下列按钮触发: **gis 客户端** 正在生成. 通话 `SocialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID)` 没有效果.

相反,确保你 [订阅认证状态](https://npmcn.com/package/%40abacritt/angularx-social-login/#readme-subscribe-to-the-authentication-state) 并添加以下内容: `GoogleSigninButtonDirective` 切入到您的组件模板, 将“ 与 Google 一起签名” 按钮 :

还有

看看这个 [谷歌按钮生成器](https://developers.google.com/identity/gsi/web/tools/configurator)。 。 。 . [链接到按钮属性](https://developers.google.com/identity/gsi/web/reference/html-reference#element_with_class_g_id_signin)

```html
<asl-google-signin-button type='icon' size='medium'></asl-google-signin-button>
```

选项 :

| 名称 | 类型 | 数值 | 默认 |
| --- | --- | --- | --- |
| 类型 | 字符串 | icon 或 标准 | 漫画 |
| 大小 | 字符串 | “ 小”、“ 中” 或“ 大” | 中间 |
| 形状 | 字符串 | "平方","圆","出"或"矩" | "矩形" (中文(简体) ) |
| 文本 | 字符串 | “ 与 ” 、 “ 与 ” 或 “ 继续 ” | 签名( w) |
| 宽度 | 字符串 | '200 - 400 ' 号 |  |
| 主题 | 字符串 | 外线, “ 已填入 蓝色” 或 “ 已填入 黑色” | 外线 |
| 图标( a) | 字符串 | "左"或"中间" | 左边 |

这只有在 `GoogleLoginProvider` 注册于 [社会服务](https://npmcn.com/package/%40abacritt/angularx-social-login/#readme-import-the-module)。 。 。 .

### 刷新google Auth 托肯语

一旦用户登录在手动刷新令牌方法中,即可被触发

```javascript

import { SocialAuthService } from "@abacritt/angularx-social-login";
import { GoogleLoginProvider } from "@abacritt/angularx-social-login";

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

  constructor(private authService: SocialAuthService) { }

  refreshToken(): void {
    this.authService.refreshAuthToken(GoogleLoginProvider.PROVIDER_ID);
  }

}
```

### 请求google 访问托肯

一旦一个用户登录在访问令牌上,就可以要求我们指定的范围 `GoogleInitOptions.scopes`,然后可以重新使用此访问符,以拨打 google apis

```typescript

import { HttpClient } from '@angular/common/http';
import { SocialAuthService } from "@abacritt/angularx-social-login";
import { GoogleLoginProvider } from "@abacritt/angularx-social-login";

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

  private accessToken = '';

  constructor(private authService: SocialAuthService, private httpClient: HttpClient) { }

  getAccessToken(): void {
    this.authService.getAccessToken(GoogleLoginProvider.PROVIDER_ID).then(accessToken => this.accessToken = accessToken);
  }

  getGoogleCalendarData(): void {
    if (!this.accessToken) return;

    this.httpClient
      .get('https://www.googleapis.com/calendar/v3/calendars/primary/events', {
        headers: { Authorization: `Bearer ${this.accessToken}` },
      })
      .subscribe((events) => {
        alert('Look at your console');
        console.log('events', events);
      });
  }
}
```

### 刷新 google 访问托肯

一旦用户登录并获得访问令牌,访问令牌即可被刷新(已撤销)

```typescript

import { SocialAuthService } from "@abacritt/angularx-social-login";
import { GoogleLoginProvider } from "@abacritt/angularx-social-login";

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

  constructor(private authService: SocialAuthService) { }

  refreshToken(): void {
    this.authService.refreshAccessToken(GoogleLoginProvider.PROVIDER_ID);
  }

}
```

### 订阅认证状态

用户登录或注销时,会通知您。 你得到一个 `SocialUser` 对象在用户登录时 `null` 用户登录时. `SocialUser` 对象包含基本用户信息,如名称、电子邮件、相片 URL 等 `auth_token`。您可以联系 `auth_token` 到您的服务器,以认证服务器中的用户,并从服务器中调用 API .

```javascript
import { SocialAuthService } from "@abacritt/angularx-social-login";
import { SocialUser } from "@abacritt/angularx-social-login";

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

  user: SocialUser;
  loggedIn: boolean;

  constructor(private authService: SocialAuthService) { }

  ngOnInit() {
    this.authService.authState.subscribe((user) => {
      this.user = user;
      this.loggedIn = (user != null);
    });
  }

}
```

### 显示用户信息

```html
<img src="{{ user.photoUrl }}" referrerpolicy="no-referrer">
<div>
  <h4>{{ user.name }}</h4>
  <p>{{ user.email }}</p>
</div>
```

## 自定义提供者

我们可以使用自定义提供者,执行我们自己的逻辑和需要,例如:

```typescript
@Injectable({ providedIn: 'root' })
export class MyCustomLoginProvider extends BaseLoginProvider {
  public static readonly PROVIDER_ID = 'CUSTOM' as const;

  constructor(/* infinite list of dependencies*/) {}
}
```

```typescript
@NgModule({
  declarations: [AppComponent, NavbarComponent, DemoComponent],
  imports: [BrowserModule, FormsModule, SocialLoginModule],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: true,
        lang: 'en',
        providers: [
          {
            id: MyCustomLoginProvider.PROVIDER_ID,
            provider: MyCustomLoginProvider,
          },
        ],
      } as SocialAuthServiceConfig,
    },
  ],
```

## 指定初始化时的自定义范围、字段等

```javascript
const fbLoginOptions = {
  scope: 'pages_messaging,pages_messaging_subscriptions,email,pages_show_list,manage_pages',
  return_scopes: true,
  enable_profile_selector: true
}; // https://developers.facebook.com/docs/reference/javascript/FB.login/v2.11

const googleLoginOptions: GoogleInitOptions = {
  oneTapEnabled: false, // default is true
  scopes: 'https://www.googleapis.com/auth/calendar.readonly'
}; // https://developers.google.com/identity/oauth2/web/guides/use-token-model#initialize_a_token_client

const vkLoginOptions = {
  fields: 'photo_max,contacts', // Profile fields to return, see: https://vk.com/dev/objects/user
  version: '5.131', // https://vk.com/dev/versions
}; // https://vk.com/dev/users.get

let config = [
  {
    id: GoogleLoginProvider.PROVIDER_ID,
    provider: new GoogleLoginProvider("Google-OAuth-Client-Id", googleLoginOptions)
  },
  {
    id: FacebookLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider("Facebook-App-Id", fbLoginOptions)
  },
  {
    id: VKLoginProvider.PROVIDER_ID,
    provider: new VKLoginProvider("VK-App-Id", vkLoginOptions)
  },
];
```

## 指定登录时的自定义范围、字段等

```javascript
const fbLoginOptions = {
  scope: 'pages_messaging,pages_messaging_subscriptions,email,pages_show_list,manage_pages'
}; // https://developers.facebook.com/docs/reference/javascript/FB.login/v2.11

this.authService.signIn(FacebookLoginProvider.PROVIDER_ID, fbLoginOptions);
```

## 供应商

| 提供者 | 文档 |
| --- | --- |
| 微软 Login 提供器 | [链接](https://npmcn.com/package/%40abacritt/angularx-social-login/microsoft-provider.md) |

## 运行演示应用程序

```sh
ng build angularx-social-login
ng serve
```

## 装入处理出错( L)

要处理错误和加载的事件, 您可以使用 `BaseLoginProvider` 从您的对象 `SocialAuthServiceConfig`

```typescript
// inject the SOCIAL_AUTH_CONFIG into your component
providerConfig: SocialAuthServiceConfig | Promise<SocialAuthServiceConfig> = inject(SOCIAL_AUTH_CONFIG);

...

async SetUpProviderHandling() {
  // get the injected providerConfig as a SocialAuthServiceConfig.
  const providerConfig = await this.providerConfig;
  // get your provider config based on the ProviderId
  const foundProviderConfig = providerConfig.providers.find(x => x.id == MyProvider.PROVIDER_ID);
  if(foundProviderConfig && foundProviderConfig.provider) {
    foundProviderConfig.provider.onHasErrorChange.subscribe(value => {
      // handle errors on change here
    });
    // set the base has error result here.
    const hasError = foundProviderConfig.provider.hasError;

    foundProviderConfig.provider.onIsLoadedChange.subscribe(value => {
      // handle isLoading on change here
    });
    // set the base isLoaded result here.
    const hasError = foundProviderConfig.provider.isLoaded;
  }
}
```

## 常见问题

### @abacritt/angularx-social-login 是什么？

Angular 19 的社会登录和认证模块\. 支持Google,Facebook,亚马逊和VK认证\. 也可扩展到其他供应商\.

### 如何安装 @abacritt/angularx-social-login？

在项目目录运行 npm install @abacritt/angularx-social-login，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@angular/common（\>=21\.2\.6）、@angular/core（\>=21\.2\.6）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @abacritt/angularx-social-login 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @abacritt/angularx-social-login 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @abacritt/angularx-social-login 可以商用吗？

@abacritt/angularx-social-login 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @abacritt/angularx-social-login 的下载量有多少？

根据 npm 官方下载统计，@abacritt/angularx-social-login 在 2026/10/05 – 2026/11/03 这 30 天内被下载 362,236 次，日均约 12,075 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @abacritt/angularx-social-login 还在维护吗？

最新版本 2\.6\.0 发布于 2026/03/28（7 个月前）；至今共发布 23 个版本，其中过去 12 个月发布了 1 个；首次发布于 2022/04/15。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

