Using Angular with Supabase for Full-Stack......

Using Angular with Supabase for Full-Stack Applications

Using Angular with Supabase for Full-Stack Applications

What is Supabase?


Supabase is an open-source BaaS that provides a PostgreSQL database, real-time APIs, authentication, and storage services out of the box. It's similar to Firebase but built on the robust and open PostgreSQL system, offering SQL compatibility and powerful query capabilities.


Key Features of Supabase:


  • PostgreSQL database: Fully-featured relational database with SQL support.


  • Real-time subscriptions: Automatically sync data between client and server.


  • Authentication: Built-in support for email/password and third-party login providers.


  • Storage: Handles file storage with access control.


Prerequisites


Before we get started, ensure that you have the following tools and software installed:


1. Node.js and npm: Install Node.js, which comes with npm, for managing dependencies.


2. Angular CLI: Install the Angular CLI by running npm install -g @angular/cli.


3. Supabase Account: Create an account at Supabase and set up a new project.


Setting Up Supabase


1. Create a Supabase Project


Once you're logged into Supabase, follow these steps:


  • Navigate to your Supabase dashboard.


  • Click on "New Project" and give it a name.


  • Select a database region and set your password.


  • Wait for Supabase to provision your project.


2. Setting Up Your Database


CREATE TABLE posts (
 id serial PRIMARY KEY,
 title text,
 content text,
 created_at timestamp DEFAULT now()
);


Setting Up Angular with Supabase


1. Create a New Angular Project


ng new angular-supabase-app


cd angular-supabase-app


2. Install Supabase SDK


npm install @supabase/supabase-js


3. Initialize Supabase in Angular


ng generate service services/supabase


In the generated supabase.service.ts file, import and initialize Supabase:


import { Injectable } from '@angular/core';
import { createClient, SupabaseClient } from '@supabase/supabase-js';

// Supabase API details
const SUPABASE_URL = 'https://your-supabase-url.supabase.co';
const SUPABASE_ANON_KEY = 'your-supabase-anon-key';

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

 constructor() {
  this.supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
 }

 // Fetch posts from Supabase
 async getPosts() {
  const { data, error } = await this.supabase
   .from('posts')
   .select('*');
  return { data, error };
 }

 // Add a new post
 async addPost(title: string, content: string) {
  const { data, error } = await this.supabase
   .from('posts')
   .insert([{ title, content }]);
  return { data, error };
 }
}


4. Using Supabase in Your Angular Components


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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 posts: any[] = [];

 constructor(private supabaseService: SupabaseService) {}

 async ngOnInit() {
  const { data, error } = await this.supabaseService.getPosts();
  if (error) {
   console.error('Error fetching posts:', error);
  } else {
   this.posts = data;
  }
 }

 async addPost(title: string, content: string) {
  const { data, error } = await this.supabaseService.addPost(title, content);
  if (error) {
   console.error('Error adding post:', error);
  } else {
   this.posts.push(data[0]);
  }
 }
}


In your app.component.html, create a simple form and list to display posts:


<div>
 <h1>Supabase Posts</h1>

 <form (submit)="addPost(title.value, content.value)">
  <input #title placeholder="Title" required>
  <textarea #content placeholder="Content" required></textarea>
  <button type="submit">Add Post</button>
 </form>

 <ul>
  <li *ngFor="let post of posts">
   <h3>{{ post.title }}</h3>
   <p>{{ post.content }}</p>
  </li>
 </ul>
</div>


Real-Time Updates


this.supabase
 .from('posts')
 .on('INSERT', payload => {
  this.posts.push(payload.new);
 })
 .subscribe();


With this in place, new posts will automatically appear in your app without refreshing the page


Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts