Create an Angular todo list with azure static web apps Part 4

In this series about Azure static web apps, we created an Angular Todo list app, an Azure function using JavaScript and linked both together. If you want to have a look at the previous parts, here are the links

In this post, we will store the todos in Cosmos DB and read it from our Azure function.

Create Cosmos DB

Azure Cosmos DB gives you a free account with upto 400 RU/s. You can use it for this demo. Go to Azure Portal, Click New Resource -> Under Databases select Azure Cosmos DB, choose the API as SQL API and add the account name, resource group and region and leave everything else with the default value then click Review + Create then Create.

Once the Azure Cosmos DB account is created, open it and go to Data Explorer and from the toolbar click New Database and give it a name

Once the database is created, click the three dots near the database name and click New Container. Provide a name for the container and type /id as the partition key then click ok

From the left menu click Keys and copy the PRIMARY CONNECTION STRING.

Azure Function Settings

To connect to the Azure Cosmos DB, we we will need to store the connection string somewhere. For this purpose, we will use the file local.settings.json under api folder.

Add a new key under the values key and name it CosmosConnectionString and paste the Cosmos DB connection string copied earlier.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "CosmosConnectionString":""
  },"Host": {
    "CORS": "*"
  }
}

The local.settings.json file is not added to Git and should not be. This should include the connection strings and any secrets used locally.

Connect to Cosmos from the APIs

We have the database ready now and the connection string is set in our api. To read data from Cosmos, we need to install the package @azure/cosmos. Open command prompt and navigate to the api folder that has the function project and run the following command

npm i @azure/cosmos

Now open the index.js file inside the api/GetTodoList folder and paste the following code

const CosmosClient = require('@azure/cosmos').CosmosClient;

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    let cosmosClient = new CosmosClient(process.env['CosmosConnectionString']);
    let database = cosmosClient.database('todos');
    let container = database.container('todolist');
    let {resources} = (await container.items.query('SELECT c.id,c.title,c.isCompleted FROM c').fetchAll());

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: resources
    };
}

The code is straight forward, in line 1, we imported the CosmosClient class which will be used to connect to Cosmos DB. This is like an EntityFramework DBContext. Line 5,6, and 7 we create a client instance, use it to get a reference to the database and the container that has our data.

In line 8, we query the container to return only the id, title and isCompleted fields and return the results.

You can see that the field names are now pascal named (title instead of Title), you will have to update the binding in the TodoList component

 <td><input type="checkbox" [checked]="todo.isCompleted" disabled></td>

Test

Run your api project with func start and your Angular app with ng serve. You should see an empty list. Go back to your Cosmos DB instance in Azure Portal, click Data Explorer, select the db then the container and choose Items. You can add a new item by clicking the New Item button on the toolbar and then click Save. Repeat the process to add few items

Now try to refresh your app and you should see the data displayed in the Angular app

Deployment

Commit and push your changes and wait for the workflow action to finish. If you tried your site now it will not work as the function has no idea about the connection string. To add a new connection string, open your Azure Static Web App, click on Configuration and then click Add. Type CosmosConnectionString as the name and paste the connection string for the Cosmos DB in the value field. Save and refresh your app and now you should see the application displaying the data you saved in Cosmos DB

Source code: https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp

Create an Angular todo list with azure static web apps Part 3

In part one of the serious, we created the SPA with Angular, deployed it to Azure Static Web Apps. In Part 2, we created the API part. In this post, we will link the both the Frontend with the Backend.

Create the Listing Component

Open CMD and navigate to the folder that has your angular app then run the command ng g c TodoList. This will generate an Angular component with the name TodoListComponent. Open the code for this component and put the following code.

<h1>Your Todos</h1>
<table>
    <thead> 
        <tr>
            <th>Todo</th>
            <th>Complete</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let todo of todos">
            <td>{{todo.Title}}</td>
            <td><input type="checkbox" checked="{{todo.Complete}}" readonly></td>
        </tr>
    </tbody>
</table>
import { TodoService } from './../todo.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-todo-list',
  templateUrl: './todo-list.component.html',
  styleUrls: ['./todo-list.component.scss'],
})
export class TodoListComponent implements OnInit {
  todos: any;
  constructor(private todoService: TodoService) {}

  ngOnInit(): void {
    this.todoService.getTodoList().then((response) => response.json()).then(data =>{
       this.todos = data;
       console.log(data);
    });
  }
}

table{
    width:100%;
    border: 1px;
}

table tr th{
    background-color: lightslategray;
}

table tr td{
    text-align: center;
}

The first part is the HTML and the second is the component code and the third is the CSS.

Create the Todo Service

To communicate with the API, we will create an Angular service. Navigate to the app folder under the src directory and run the command ng g s Todo. This will create a new service with the name TodoService. The code should look like this

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TodoService {



 getTodoList() {
    return fetch('api/GetTodoList');
  }
}

The getTodoList function calls the fetch method to make an Ajax request to the API. Notice the URL is just api/GetTodoList because our Angular app and the API runs in the same domain and the paths will be relative. If you are running it locally, the path would be prefixed with the correct URL. Ex:  return fetch('http://localhost:7071/api/GetTodoList');

Routing

Nowe we need to make the default route redirects to the TodoComponent. Open the app\app-routing.module.ts and change it as below:

import { SaveToDoComponent } from './save-to-do/save-to-do.component';
import { TodoListComponent } from './todo-list/todo-list.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    component: TodoListComponent,
    path: '',
  },
  {
    component: TodoListComponent,
    path: 'todolist',
  },
  {
    component: SaveToDoComponent,
    path: 'new',
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Open the app.component.html and remove all the code after the style and only leave the <router-outlet></router-outlet>.

Testing our changes

Now commit and push the changes and wait for the GitHub action to run. Once deployment is completed, try your site and it should look like this:

Now you have a fully functioning SPA running in Azure Static Web App. In the next articles, we will refine it more to connect to a storage backend and do more authentication.

You can try the source code yourself at https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp

Create an Angular todo list with azure static web apps Part 2

In the previous post , we created the first part of our todo list that will be deployed to Azure Static Web App service. In this post, we will add the backend as an Azure Function

List ToDos Azure Function

Create a new folder with the name api then make sure you have Azure Functions extension install in VS code. Press F1, this will show the command window in vs code, type functions and select Azure Functions: Create New Project, choose api\GetTodoList as the folder for the Azure Function, choose JavaScript as the language (As per today, Static Web Apps only support JavaScript functions), HttpTriger as the trigger and GetTodoList as the function name and finally Anonymous as the authentication method. This will create all the files needed for you function.

Get Todos implementation

Now, let’s put a dummy implementation for the GetToDos function.

Edit the index.js file with the following code. This will return 4 Todos. The implementation can be changed later to connect to any other data source

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    const responseMessage =  [
         { Title : "Read Microfronts book", IsCompleted : false},
         { Title : "Post a blog about Project Tye", IsCompleted : false},
         { Title : "Get some exercises", IsCompleted : true},
         { Title : "Do more stuff", IsCompleted : false},
    ];

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

Go to your Az Functions Tools and run the function, it should show the funcion URL in the console window

Hit http://localhost:7071/api/GetTodoList in your browser and you should be able to see the results in JSON

You can follow the same steps to create another function to add and edit Todo.

Deploy the API to Azure Static Web App

Commit and push the changes to your GitHub Repo and watch GitHub actions building and packaging the application. All the code in the repo will be built and packaged including the Azure Function.

Validating deployment

Once the GitHub action finishes and show a success mark, open Azure Portal and go to your Azure Static Web App then click Functions on the left menu. You should be able to see the GetTodoList function there.

Function Configuration

Once you have the function deployed, you can add configuration keys under Configuration section. One of the configuration is APPINSIGHTS_INSTRUMENTATIONKEY that can be used to link your static web app to an application insights instance which will recive all the logs made by your function using the context.log function.

Testing your API

Its time to make sure everything works fine. Click the overview tab then click on the URL for the site, it should open the static site web created in previous post. To access the API, you have to append api/FUNCTION_NAME. in our case, it will be URL/api/GetTodoList

Inspect function behavior with application insights

Since our function is now working fine, a bonus point would be to check the logs generated from it. After you create an application insights instance and add a configuration key APPINSIGHTS_INSTRUMENTATIONKEY with the app insights instrumention key, invoke the function few times then go to your app insights instance and click Search from the left menu. You should be able to see the logs

As you can see above, not only you can see the messages logged from the function but also from the azure functions runtime.

In next post, we will link the SPA to our APIs and do more fancy stuff.

The source code can be found on my GitHub repository. All you need to do is to fork it, create a new static web app and link it to the repo. https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp

Create an Angular todo list with azure static web apps Part 1

This article is part of [#ServerlessSeptember](https://aka.ms/ServerlessSeptember2020). You’ll find other helpful articles, detailed tutorials, and videos in this all-things-Serverless content collection. New articles from community members and cloud advocates are published every week from Monday to Thursday through September. 
 
Find out more about how Microsoft Azure enables your Serverless functions at [https://docs.microsoft.com/azure/azure-functions/](https://docs.microsoft.com/azure/azure-functions/?WT.mc_id=servsept20-devto-cxaall). 

If you missed my session on SeverlessDaysANZ, you can watch on YouTube

In this post, I will create a To Do List app using Angular and we will host it on the newly introduced Azure service called Static Web Apps.

Project Setup

Azure static web app is connected to GitHub repo, and the first thing to do is to create a new repo under your github account. Once you create it, clone it to your local machine and run the following commands. Make sure you have angular-cli tools installed

ng new AzTodoList

Choose yes for routing and select your preferred css processor and hit enter to create the project and install all needed packages. Once all packages are installed, run ng serve to make sure the app works fine. You should have something like this running on port 4200

Make sure all files exist in the root folder where you cloned the GitHub repo. If you cloned the repo in a folder called ToDoList and then ran the command ng new inside it, it will create another subfolder. If this happened, make sure to move the files in the inner folder to the ToDoList folder. Otherwise, the GitHub action won’t work since it will fail to determine the programing language used. Your folder structure should look like this:

Now commit the source code with git add . to add all files followed by git commit -m "Initial commit" and finally git push origin master to push the files to GitHub.

Create Azure Static Web App

Open Azure portal and create a new static web app, log in to your GitHub account and choose the ToDoList app

Click on Next: Build to move to the next screen and configure it as below. The artifact location is dist/AzTodoList but it can be different in your case depending on your angular project name. You can get the exact path from your angular.json file or run ng build and check your folder structure.

When you create the app, it will automatically created the necessary CI/CD on GitHub using GitHub Actions and you can view that by clicking on the link “Thank you for using Azure Static Web App! We have not received any content for your site yet. Click here to check the status of your GitHub Action runs.” . You can view the build status by going to your GitHub repo and click Actions

As you can see above, it failed few times because I put the Angular app in a folder inside the repo. Once I moved all the files from within the inner folder to the root folder, it worked.

Test the app

Now go back to your Azure Portal and in the overview tab for the static web app, click Browse and this is what you should see

In the next post, we will add the APIs that will be used to retrieve, add and delete ToDos

Source code: https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp