Supabase和Angular快速入门指南

583 阅读5分钟

Supabase和Angular快速入门指南

这个例子提供了使用Supabase和Angular建立一个简单的用户管理应用(从头开始!)的步骤。

这个例子提供了使用Supabase和Angular建立一个简单的用户管理应用(从头开始!)的步骤。它包括:

  • Supabase数据库:一个用于存储用户数据的Postgres数据库。
  • SupabaseAuth:用户可以用魔法链接登录(没有密码,只有电子邮件)。
  • Supabase存储:用户可以上传照片。
  • 行级安全:数据受到保护,个人只能访问自己的数据。
  • 即时API:当你创建你的数据库表时,API将自动生成。

在本指南结束时,你将拥有一个允许用户登录并更新一些基本的个人资料细节的应用程序。

点击这个按钮,应用程序将:

  • 在Supabase中启动并准备Postgres数据库。
  • 在Vercel中启动该应用程序。
  • 在你自己的GitHub账户中分叉这个例子。
  • 用所有必要的环境变量准备部署的应用程序。

如果你想自己动手,让我们开始吧!

GitHub

项目设置

在我们开始构建之前,我们要设置我们的数据库和API。这很简单,就是在Supabase中启动一个新的项目,然后在数据库中创建一个 "模式"。

创建一个项目

  1. 进入app.supabase.com
  2. 点击 "新项目"。
  3. 输入你的项目细节。
  4. 等待新数据库的启动。

设置数据库模式

现在我们要设置数据库模式。我们可以使用SQL编辑器中的 "User Management Starter "快速入门,或者你可以直接复制/粘贴下面的SQL并自己运行。

SQL

-- Create a table for public "profiles"
create table profiles (
  id uuid references auth.users not null,
  updated_at timestamp with time zone,
  username text unique,
  avatar_url text,
  website text,

  primary key (id),
  unique(username),
  constraint username_length check (char_length(username) >= 3)
);

alter table profiles enable row level security;

create policy "Public profiles are viewable by everyone."
  on profiles for select
  using ( true );

create policy "Users can insert their own profile."
  on profiles for insert
  with check ( auth.uid() = id );

create policy "Users can update own profile."
  on profiles for update
  using ( auth.uid() = id );

-- Set up Realtime!
begin;
  drop publication if exists supabase_realtime;
  create publication supabase_realtime;
commit;
alter publication supabase_realtime add table profiles;

-- Set up Storage!
insert into storage.buckets (id, name)
values ('avatars', 'avatars');

create policy "Avatar images are publicly accessible."
  on storage.objects for select
  using ( bucket_id = 'avatars' );

create policy "Anyone can upload an avatar."
  on storage.objects for insert
  with check ( bucket_id = 'avatars' );

用户界面

1. Go to the "SQL" section.
2. Click "User Management Starter".
3. Click "Run".

获取API密钥

现在你已经创建了一些数据库表,你已经准备好使用自动生成的API插入数据。我们只需要从API设置中获取URL和anon 密钥。

1. Go to the "SQL" section.
2. Click "User Management Starter".
3. Click "Run".

构建应用程序

让我们开始从头开始构建Angular应用程序。

初始化一个Angular应用程序

我们可以使用Angular CLI来初始化一个名为supabase-angular 的应用程序。

JavaScript

npx ng new supabase-angular --routing false --style css
cd supabase-angular

然后让我们安装唯一的额外依赖:supabase-js

外壳

npm install @supabase/supabase-js

最后,我们要在environment.ts 文件中保存环境变量。我们所需要的是API URL和你之前复制的anon 密钥。这些变量将暴露在浏览器上,这完全没有问题,因为我们在数据库上启用了行级安全

JavaScript

environment.ts

export const environment = {
  production: false,
  supabaseUrl: "YOUR_SUPABASE_URL",
  supabaseKey: "YOUR_SUPABASE_KEY"
};

现在我们已经有了API凭证,让我们用ng g s supabase 创建一个SupabaseService来初始化Supabase客户端并实现与Supabase API通信的功能。

脚本

src/app/supabase.service.ts

import { Injectable } from '@angular/core';
import {AuthChangeEvent, createClient, Session, SupabaseClient} from '@supabase/supabase-js';
import {environment} from "../environments/environment";

export interface Profile {
  username: string;
  website: string;
  avatar_url: string;
}

@Injectable({
  providedIn: 'root'
})
export class SupabaseService {
  private supabase: SupabaseClient;

  constructor() {
    this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey);
  }

  get user() {
    return this.supabase.auth.user();
  }

  get session() {
    return this.supabase.auth.session();
  }

  get profile() {
    return this.supabase
      .from('profiles')
      .select(`username, website, avatar_url`)
      .eq('id', this.user?.id)
      .single();
  }

  authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
    return this.supabase.auth.onAuthStateChange(callback);
  }

  signIn(email: string) {
    return this.supabase.auth.signIn({email});
  }

  signOut() {
    return this.supabase.auth.signOut();
  }

  updateProfile(profile: Profile) {
    const update = {
      ...profile,
      id: this.user?.id,
      updated_at: new Date()
    }

    return this.supabase.from('profiles').upsert(update, {
      returning: 'minimal', // Don't return the value after inserting
    });
  }

  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);
  }
}

还有一个可选的步骤是更新CSS文件src/index.css ,使应用程序看起来更漂亮。你可以在这里找到这个文件的全部内容。

设置一个登录组件

让我们设置一个Angular组件来管理登录和注册。我们将使用Magic Links,所以用户可以用他们的电子邮件登录,而不需要使用密码。用ng g c auth Angular CLI命令创建一个AuthComponent

脚本

src/app/auth.component.ts

import { Component } from '@angular/core';
import {SupabaseService} from "./supabase.service";

@Component({
  selector: 'app-auth',
  template: `
    <div class="row flex flex-center">
      <form class="col-6 form-widget">
        <h1 class="header">Supabase + Angular</h1>
        <p class="description">Sign in via magic link with your email below</p>
        <div>
          <input
            #input
            class="inputField"
            type="email"
            placeholder="Your email"
          />
        </div>
        <div>
          <button
            type="submit"
            (click)="handleLogin(input.value)"
          class="button block"
          [disabled]="loading"
          >
          {{loading ? 'Loading' : 'Send magic link'}}
          </button>
        </div>
      </form>
    </div>
  `,
})
export class AuthComponent {
  loading = false;

  constructor(private readonly supabase: SupabaseService) { }

  async handleLogin(input: string) {
    try {
      this.loading = true;
      await this.supabase.signIn(input);
      alert('Check your email for the login link!');
    } catch (error) {
      alert(error.error_description || error.message)
    } finally {
      this.loading = false;
    }
  }
}

帐户页面

在用户登录后,我们可以让他们编辑他们的个人资料细节并管理他们的账户。用ng g c account Angular CLI命令创建一个AccountComponent

脚本

src/app/account.component.ts

import {Component, Input, OnInit} from '@angular/core';
import {Profile, SupabaseService} from "./supabase.service";
import {Session} from "@supabase/supabase-js";

@Component({
  selector: 'app-account',
  template: `
    <div class="form-widget">
      <div>
        <label for="email">Email</label>
        <input id="email" type="text" [value]="session?.user?.email" disabled/>
      </div>
      <div>
        <label for="username">Name</label>
        <input
          #username
          id="username"
          type="text"
          [value]="profile?.username ?? ''"
        />
      </div>
      <div>
        <label for="website">Website</label>
        <input
          #website
          id="website"
          type="url"
          [value]="profile?.website ?? ''"
        />
      </div>

      <div>
        <button
          class="button block primary"
          (click)="updateProfile(username.value, website.value)"
          [disabled]="loading"
        >
          {{loading ? 'Loading ...' : 'Update'}}
        </button>
      </div>

      <div>
        <button class="button block" (click)="signOut()">
          Sign Out
        </button>
      </div>
    </div>
  `
})
export class AccountComponent implements OnInit {
  loading = false;
  profile: Profile | undefined;

  @Input() session: Session | undefined;

  constructor(private readonly supabase: SupabaseService) { }

  ngOnInit() {
    this.getProfile();
  }

  async getProfile() {
    try {
      this.loading = true;
      let {data: profile, error, status} = await this.supabase.profile;

      if (error && status !== 406) {
        throw error;
      }

      if (profile) {
        this.profile = profile;
      }
    } catch (error) {
      alert(error.message)
    } finally {
      this.loading = false;
    }
  }

  async updateProfile(username: string, website: string, avatar_url: string = '') {
    try {
      this.loading = true;
      await this.supabase.updateProfile({username, website, avatar_url});
    } catch (error) {
      alert(error.message);
    } finally {
      this.loading = false;
    }
  }

  async signOut() {
    await this.supabase.signOut();
  }
}

启动!

现在我们已经有了所有的组件,让我们来更新AppComponent

JavaScript

src/app/app.component.ts

import {Component, OnInit} from '@angular/core';
import {SupabaseService} from "./supabase.service";

@Component({
  selector: 'app-root',
  template: `
  <div class="container" style="padding: 50px 0 100px 0">
    <app-account *ngIf="session; else auth" [session]="session"></app-account>
    <ng-template #auth>
      <app-auth></app-auth>
    </ng-template>
  </div>
  `
})
export class AppComponent implements OnInit {
  session = this.supabase.session;

  constructor(private readonly supabase: SupabaseService) { }

  ngOnInit() {
    this.supabase.authChanges((_, session) => this.session = session);
  }
}

一旦完成,在终端窗口运行这个。npm run start

然后打开浏览器到localhost:4200,你应该看到完成的应用程序。

奖励:个人资料照片

每个Supabase项目都配置了用于管理照片和视频等大文件的存储器。

创建一个上传小工具

让我们为用户创建一个头像,以便他们可以上传个人资料照片。用ng g c avatar Angular CLI命令创建一个AvatarComponent

JavaScript

src/app/avatar.component.ts

import {Component, EventEmitter, Input, Output} from '@angular/core';
import {SupabaseService} from "./supabase.service";
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";

@Component({
  selector: 'app-avatar',
  template: `
    <div>
      <img
        *ngIf="_avatarUrl"
        [src]="_avatarUrl"
        alt="Avatar"
        class="avatar image"
        style="height: 150px; width: 150px"
      ></div>
    <div *ngIf="!_avatarUrl" class="avatar no-image" style="height: 150px; width: 150px"></div>
    <div style="width: 150px">
      <label class="button primary block" for="single">
        {{uploading ? 'Uploading ...' : 'Upload'}}
      </label>
      <input
        style="visibility: hidden;position: absolute"
        type="file"
        id="single"
        accept="image/*"
        (change)="uploadAvatar($event)"
        [disabled]="uploading"
      />
    </div>
  `,
})
export class AvatarComponent {
  _avatarUrl: SafeResourceUrl | undefined;
  uploading = false;

  @Input()
  set avatarUrl(url: string | undefined) {
    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);
      this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data));
    } catch (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 fileName = `${Math.random()}.${fileExt}`;
      const filePath = `${fileName}`;

      await this.supabase.uploadAvatar(filePath, file);
      this.upload.emit(filePath);
    } catch (error) {
      alert(error.message);
    } finally {
      this.uploading = false;
    }
  }
}

添加新的小工具

然后我们可以在AccountComponent的HTML模板上面添加小工具。

JavaScript

src/app/account.component.ts

template: `
<app-avatar
    [avatarUrl]="this.profile?.avatar_url"
    (upload)="updateProfile(username.value, website.value, $event)">
</app-avatar>

<!-- input fields -->
`