Skip to content

Use Angular with Appwrite

Tyler Ruff edited this page Oct 25, 2022 · 1 revision

Connecting an Angular application to the Appwrite self-hosted backend as a service is quite simple.

  1. First, install the Appwrite client in your applications:
npm install appwrite
  1. Next, get your server's configuration and bring it to /src/environments/environments.ts, use the following template:
export const environment = {
  production: false,
  APP_ENDPOINT: "[APP_ENDPOINT]",
  APP_PROJECT: "[PROJECT-ID]"
};
  1. Now, you have to create an api.ts helper for the API service. Create a folder called "helpers" inside of the "app" folder. Add the following to a new file called "api.ts":
import { Server } from './../utils/config';
import { Client, Account, ID } from 'appwrite';

export class Api {
    private static sdk: Client | null;

    static provider(){
        if(this.sdk) return this.sdk;
        let client = new Client()
            .setEndpoint(Server.endpoint)
            .setProject(Server.project)
            .setLocale('en-US');
        this.sdk = client;
        return this.sdk;
    }
}

Next, we will learn how to Query Databases and Collections.

  1. First, you will have to create a database and collection. We will assume the following schema:
{
 "title": "string",
 "content": "string"
}
  1. Next, you will have to create a model for the data you want to query. Create a folder in the "app" folder called "models". Create a file in "models" called Page.ts, and add the following:
import { Models } from 'appwrite';

export type Page = Models.Document & {
  title: string,
  content: string
}
  1. Finally, you can select all data from the database using the following code (in your component):
  • [...].component.ts
import { Api } from './../helpers/api';

import { Service } from '../models/Service';
import { Databases, Query } from "appwrite";
...
export class [...]Component implements OnInit {
 public pages: Page[];
 constructor(){
  const databases = new Databases(Api.provider());
  let getPages = databases.listDocuments(
      "[DATABASE-ID]",
      "[COLLECTION-ID]"
  );
  getPages.then((response) => {
      this.pages = response.documents as Page[];
    }, function (error){
      console.log(error);
  });
 }
  • [...].component.html
<ng-container *ngFor="let page of pages">
 <h1>{{ page.title }}</h1>
 <p>{{ page.content }}</p>
</ng-container>
Clone this wiki locally