用 Angular 构建一个用户管理应用
本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:
🌐 This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:
- Supabase 数据库 - 一个用于存储用户数据的 Postgres 数据库,并且有 行级安全,所以数据是受保护的,用户只能访问自己的信息。
- Supabase Auth - 允许用户注册和登录。
- Supabase 存储 - 允许用户上传个人头像。

如果你在跟着这个指南操作时遇到困难,你可以在GitHub上找到完整示例。
🌐 If you get stuck while working through this guide, you can find the full example on GitHub.
项目设置 #
🌐 Project setup
在你开始构建之前,你需要先设置数据库和 API。你可以通过在 Supabase 中启动一个新项目,然后在数据库中创建一个“架构”来完成这一步。
🌐 Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.
创建一个项目 #
🌐 Create a project
- 在 Supabase 仪表板中创建一个新项目。
- 输入你的项目详情。
- 等新数据库上线。
设置数据库模式 #
🌐 Set up the database schema
现在设置数据库模式。你可以在 SQL 编辑器中使用“用户管理入门”快速开始,也可以复制粘贴下面的 SQL 并运行。
🌐 Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.
- 在仪表板中转到SQL 编辑器页面。
- 在 参考 > 示例 选项卡下点击 用户管理入门。
- 点击运行。
你可以通过运行 db pull 命令将数据库架构拉到本地项目。查看本地开发文档获取详细说明。
🌐 You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.
supabase link --project-ref <project-id># You can get <project-id> from your project's dashboard URL: https://supabase.nodejs.cn/dashboard/project/<project-id>supabase db pull获取 API 详情 #
🌐 Get API details
要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。
🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.
正在构建应用 #
🌐 Building the app
从零开始构建 Angular 应用吧。
🌐 Start with building the Angular app from scratch.
初始化一个 Angular 应用 #
🌐 Initialize an Angular app
使用 Angular CLI 初始化一个名为 supabase-angular 的应用,并设置一些你可以根据需要更改的默认值:
🌐 Use the Angular CLI to initialize an app called supabase-angular setting some defaults that you can change to suit your needs:
npx ng new supabase-angular --routing false --style css --standalone false --ssr falsecd supabase-angular安装 supabase-js:
🌐 Install supabase-js:
npm install @supabase/supabase-js创建一个 src/environments 目录,并将你之前复制的 API URL 和密钥作为环境变量保存到一个新的 src/environments/environment.ts 文件中。
🌐 Create a src/environments directory and save API URL and key that you copied earlier as environment variables in a new src/environments/environment.ts file.
这个应用会在浏览器中暴露这些变量,这没问题,因为 Supabase 默认在所有表上启用了行级安全。
🌐 The application exposes these variables in the browser, and that's fine as Supabase enables Row Level Security by default on all tables.
export const = { : false, : 'YOUR_SUPABASE_URL', : 'YOUR_SUPABASE_PUBLISHABLE_KEY',}在配置好 API 凭证后,使用 ng g s supabase 创建一个 SupabaseService,然后添加以下代码来初始化 Supabase 客户端,并实现与 Supabase API 交互的功能。
🌐 With the API credentials in place, create a SupabaseService with ng g s supabase and add the following code to initialize the Supabase client and implement functions to communicate with the Supabase API.
import { Injectable } from '@angular/core'import { AuthChangeEvent, createClient, Session, SupabaseClient, User } from '@supabase/supabase-js'import { environment } from '../environments/environment'export interface Profile { id?: string username: string website: string avatar_url: string}@Injectable({ providedIn: 'root',})export class SupabaseService { private supabase: SupabaseClient constructor() { this.supabase = createClient(environment.supabaseUrl, environment.supabasePublishableKey) } async getUser(): Promise<User | null> { const { data, error } = await this.supabase.auth.getUser() if (error) { return null } return data.user } profile(user: User) { return this.supabase .from('profiles') .select(`username, website, avatar_url`) .eq('id', user.id) .single() } authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) { return this.supabase.auth.onAuthStateChange(callback) } signIn(email: string) { return this.supabase.auth.signInWithOtp({ email }) } signOut() { return this.supabase.auth.signOut() } updateProfile(profile: Profile) { const update = { ...profile, updated_at: new Date(), } return this.supabase.from('profiles').upsert(update) } downLoadImage(path: string) { return this.supabase.storage.from('avatars').download(path) } uploadAvatar(filePath: string, file: File) { return this.supabase.storage.from('avatars').upload(filePath, file) }}可选地,更新 src/styles.css 来美化应用。你可以在示例仓库中找到该文件的完整内容。
🌐 Optionally, update src/styles.css to style the app. You can find the full contents of this file in the example repository.
设置一个登录组件 #
🌐 Set up a sign-in component
你需要一个 Angular 组件来管理登录和注册。这个组件使用 Magic Links,所以用户可以使用邮箱登录而不需要密码。
🌐 You need an Angular component to manage sign-ins and sign-ups. The component uses Magic Links, so users can sign in with their email without using passwords.
你知道吗?
你可以自定义发送给新用户的其他邮件,包括邮件的外观、内容以及查询参数,都可以在仪表板的 认证 > 邮件 部分进行设置。
🌐 You can customize other emails sent out to new users, including the email's looks, content, and query parameters from the Authentication > Email section of the Dashboard.
使用 ng g c auth Angular CLI 命令创建一个 AuthComponent,然后添加以下代码。
🌐 Create an AuthComponent with the ng g c auth Angular CLI command and add the following code.
import { Component } from '@angular/core'import { FormBuilder, FormGroup } from '@angular/forms'import { SupabaseService } from '../supabase.service'@Component({ selector: 'app-auth', templateUrl: './auth.component.html', styleUrls: ['./auth.component.css'], standalone: false,})export class AuthComponent { loading = false signInForm: FormGroup constructor( private readonly supabase: SupabaseService, private readonly formBuilder: FormBuilder ) { this.signInForm = this.formBuilder.group({ email: '', }) } async onSubmit(): Promise<void> { try { this.loading = true const email = this.signInForm.value.email as string const { error } = await this.supabase.signIn(email) if (error) throw error alert('Check your email for the login link!') } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.signInForm.reset() this.loading = false } }}账户页面 #
🌐 Account page
用户在登录后还需要一种方式来编辑他们的个人资料信息并管理他们的账户。使用 ng g c account Angular CLI 命令创建一个 AccountComponent,并添加以下代码。
🌐 Users also need a way to edit their profile details and manage their accounts after signing in. Create an AccountComponent with the ng g c account Angular CLI command and add the following code.
import { Component, Input, OnInit } from '@angular/core'import { FormBuilder, FormGroup } from '@angular/forms'import { User } from '@supabase/supabase-js'import { Profile, SupabaseService } from '../supabase.service'@Component({ selector: 'app-account', templateUrl: './account.component.html', styleUrls: ['./account.component.css'], standalone: false,})export class AccountComponent implements OnInit { loading = false profile!: Profile updateProfileForm!: FormGroup// ... @Input() user!: User constructor( private readonly supabase: SupabaseService, private formBuilder: FormBuilder ) { this.updateProfileForm = this.formBuilder.group({ username: '', website: '', avatar_url: '', }) } async ngOnInit(): Promise<void> { await this.getProfile() const { username, website, avatar_url } = this.profile this.updateProfileForm.patchValue({ username, website, avatar_url, }) } async getProfile() { try { this.loading = true const { data: profile, error, status } = await this.supabase.profile(this.user) if (error && status !== 406) { throw error } if (profile) { this.profile = profile } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.loading = false } } async updateProfile(): Promise<void> { try { this.loading = true const username = this.updateProfileForm.value.username as string const website = this.updateProfileForm.value.website as string const avatar_url = this.updateProfileForm.value.avatar_url as string const { error } = await this.supabase.updateProfile({ id: this.user.id, username, website, avatar_url, }) if (error) throw error } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.loading = false } } async signOut() { await this.supabase.signOut() }}头像照片 #
🌐 Profile photos
添加一个让用户上传个人资料照片的方式。Supabase 为每个项目配置了 Storage,用于管理照片和视频等大文件。
🌐 Add a way for users to upload a profile photo. Supabase configures every project with Storage for managing large files like photos and videos.
创建一个上传小工具 #
🌐 Create an upload widget
使用 ng g c avatar Angular CLI 命令创建一个 AvatarComponent,然后添加以下代码。
🌐 Create an AvatarComponent with the ng g c avatar Angular CLI command and add the following code.
import { Component, EventEmitter, Input, Output } from '@angular/core'import { SafeResourceUrl, DomSanitizer } from '@angular/platform-browser'import { SupabaseService } from '../supabase.service'@Component({ selector: 'app-avatar', templateUrl: './avatar.component.html', styleUrls: ['./avatar.component.css'], standalone: false,})export class AvatarComponent { _avatarUrl: SafeResourceUrl | undefined uploading = false @Input() set avatarUrl(url: string | null) { if (url) { this.downloadImage(url) } } @Output() upload = new EventEmitter<string>() constructor( private readonly supabase: SupabaseService, private readonly dom: DomSanitizer ) {} async downloadImage(path: string) { try { const { data } = await this.supabase.downLoadImage(path) if (data instanceof Blob) { this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data)) } } catch (error) { if (error instanceof Error) { console.error('Error downloading image: ', error.message) } } } async uploadAvatar(event: any) { try { this.uploading = true if (!event.target.files || event.target.files.length === 0) { throw new Error('You must select an image to upload.') } const file = event.target.files[0] const fileExt = file.name.split('.').pop() const filePath = `${Math.random()}.${fileExt}` await this.supabase.uploadAvatar(filePath, file) this.upload.emit(filePath) } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.uploading = false } }}更新账户组件 #
🌐 Update the Account component
创建了 Avatar 组件后,更新 AccountComponent 来包含它:
🌐 With the Avatar component created, update AccountComponent to include it:
import { Component, Input, OnInit } from '@angular/core'import { FormBuilder, FormGroup } from '@angular/forms'import { User } from '@supabase/supabase-js'import { Profile, SupabaseService } from '../supabase.service'@Component({ selector: 'app-account', templateUrl: './account.component.html', styleUrls: ['./account.component.css'], standalone: false,})export class AccountComponent implements OnInit { loading = false profile!: Profile updateProfileForm!: FormGroup get avatarUrl() { return this.updateProfileForm.value.avatar_url as string } async updateAvatar(event: string): Promise<void> { this.updateProfileForm.patchValue({ avatar_url: event, }) await this.updateProfile() } @Input() user!: User constructor( private readonly supabase: SupabaseService, private formBuilder: FormBuilder ) { this.updateProfileForm = this.formBuilder.group({ username: '', website: '', avatar_url: '', }) } async ngOnInit(): Promise<void> { await this.getProfile() const { username, website, avatar_url } = this.profile this.updateProfileForm.patchValue({ username, website, avatar_url, }) } async getProfile() { try { this.loading = true const { data: profile, error, status } = await this.supabase.profile(this.user) if (error && status !== 406) { throw error } if (profile) { this.profile = profile } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.loading = false } } async updateProfile(): Promise<void> { try { this.loading = true const username = this.updateProfileForm.value.username as string const website = this.updateProfileForm.value.website as string const avatar_url = this.updateProfileForm.value.avatar_url as string const { error } = await this.supabase.updateProfile({ id: this.user.id, username, website, avatar_url, }) if (error) throw error } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { this.loading = false } } async signOut() { await this.supabase.signOut() }}你还需要把 app.module.ts 改成包含 @angular/forms 包里的 ReactiveFormsModule。
🌐 You also need to change app.module.ts to include the ReactiveFormsModule from the @angular/forms package.
import { NgModule } from '@angular/core'import { BrowserModule } from '@angular/platform-browser'import { ReactiveFormsModule } from '@angular/forms'import { AppComponent } from './app.component'import { AuthComponent } from './auth/auth.component'import { AccountComponent } from './account/account.component'import { AvatarComponent } from './avatar/avatar.component'@NgModule({ declarations: [AppComponent, AuthComponent, AccountComponent, AvatarComponent], imports: [BrowserModule, ReactiveFormsModule], providers: [], bootstrap: [AppComponent],})export class AppModule {}触发! #
🌐 Launch!
在所有组件就位后,修改 AppComponent 的内容以包含新的组件和认证逻辑:
🌐 With all the components in place, change the contents of AppComponent to include the new components and Auth logic:
Supabase Auth SDK 包含三种不同的函数,用于验证用户对应用的访问权限:
🌐 The Supabase Auth SDK contains three different functions for authenticating user access to applications:
方法总结 #
🌐 Summary of the methods
- 使用
getClaims来保护页面和用户数据。它会从存储中读取访问令牌并进行验证。本地通过 WebCrypto API 和缓存的 JWKS 端点进行处理,当项目使用非对称签名密钥(新项目的默认设置)时,或者在使用对称密钥时仅通过调用getUser来验证。返回的声明始终来自 JWT 解码,而不是用户查找。当访问令牌快到期时,getClaims会在验证前刷新会话,这就是服务器渲染会话保持活跃的方式。 [getUser](/docs/reference/javascript/auth-getuser)会向项目的 Auth 实例发起网络请求以获取用户记录,这样可以获得用户的最新信息,但需要进行一次网络请求。getSession当你需要原始会话(访问令牌、刷新令牌和过期时间)时使用。例如,将访问令牌转发到另一个服务。会话是直接从本地存储加载的,并不会重新向认证服务器验证,因此当存储与客户端共享(如 cookies、请求头)时,嵌入的用户对象不应单独信任。要验证身份,请使用getClaims验证访问令牌,或调用getUser获取一个新的、服务器确认的用户记录。
总结:使用 getClaims 来验证身份(通常用于保护页面和数据),当你需要从认证服务器获取最新的用户记录时用 getUser,而当你直接需要访问或刷新令牌时用 getSession,但不要依赖它返回的用户对象来做授权决策。
import { Component, OnInit } from '@angular/core'import { User } from '@supabase/supabase-js'import { SupabaseService } from './supabase.service'@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], standalone: false,})export class AppComponent implements OnInit { constructor(private readonly supabase: SupabaseService) {} title = 'angular-user-management' user: User | null = null async ngOnInit() { this.user = await this.supabase.getUser() this.supabase.authChanges(async () => { this.user = await this.supabase.getUser() }) }}现在在终端中运行这个应用吧:
🌐 Now run the application in a terminal:
npm run start打开浏览器访问 localhost:4200,你应该能看到完成的应用。
🌐 Open the browser to localhost:4200 and you should see the completed app.

在这个阶段,你已经有了一个完全可用的应用!
🌐 At this stage you have a fully functional application!