Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN

AWS Cloud

12.8 MEAN: Angular frontend served by Nginx

The Angular board uses the same Notes API as the React board. The project defines its own browser routes, inputs and build settings. Check the private API endpoint chosen by your exercise.

Build the Angular app

Use compatible project-local Angular CLI, Node.js and TypeScript versions. The browser-only exercise below pins a workspace, builds it and checks the result before serving it.

Angular output folder

Read the workspace builder and output settings, then inspect the actual entry and browser files. For the application-builder configuration below they are under dist/dairy-angular/browser. Server-rendered projects may also need a runtime.

Nginx configuration for MEAN

Configure a distinct site with the selected browser directory and route the API prefix to the private service. Follow the URLs emitted by the Angular build when choosing asset locations and caching. The isolated example does not depend on an existing React configuration.

Ravindra Bagale's Tip

Open the actual generated index before choosing the Nginx root. Check its browser bundle and stylesheet paths and test direct navigation. Keep existing site definitions separate from the new candidate.

Lab

खालील खाजगी lab मध्ये Angular app build करा. Generated index ने दाखवलेले JavaScript आणि CSS paths local Nginx मधून तपासा. Note add करून वेगळ्या API read आणि reload मध्ये तोच note दिसतो का पाहा.

Build a second interface while keeping the same notes service

Mauli Dairy's React board already lets the counter read and add notes. A second team wants to build an Angular board that focuses on receiving staff. Both boards should share the existing notes instead of creating independent databases. The API already knows how to read a list and create a note, and the receiving screen needs the same fields that the counter uses. This is a practical test of the architecture. If the two pieces are properly separated, changing the frontend toolkit will change the source and build process but won't require a different database contract.

Angular is an application framework that offers components, templates, request clients, forms and routing. A component is a piece of UI that has a template and some behavior. A template describes the browser elements and their relationship to the component's values. The selected project uses standalone components, the built-in Angular router and an HTTP client supplied by Angular. We will build it using the Angular CLI, a tool that can create workspaces, build projects and perform other development tasks. The existing API remains a separately running Express service. It continues to receive a normal HTTP POST or GET regardless of which framework created the browser's page.

This exercise chooses client rendering, meaning the compiled JavaScript runs in the browser and constructs the UI. Angular can also render selected routes on the server or prerender them at build time. With a hybrid configuration, different routes can use different modes. The artifact and runtime requirements then depend on which modes the project selected. The browser-only output built in this lesson does not prove that any other Angular project's entire build tree can be served as static content. Read the current project's builder configuration and rendered route choices.

Suppose the existing backend expects the path /api/notes and returns _id, text and timestamps for each note. The Angular board can present that result with a different layout, but it still needs to check the response's shape and distinguish failed requests. If a user submits “Receiving shift checked” and receives 201, the component can display exactly the note that the API confirmed. Opening a second route should retrieve the same record through the existing service. The store is the source of truth for the note. Component state describes what this particular screen knows about it right now.

Read Angular's workspace before choosing a directory to serve

An Angular workspace contains configuration for one or more projects and their build targets. In the lab angular.json tells the CLI which application it should build and which builder runs the build. A builder is the program responsible for a configured task. The application builder takes the selected entry, TypeScript settings, HTML document and style input. TypeScript allows types in the development source, which the toolchain checks and compiles. Those type declarations do not appear as additional type policy on every piece of JSON the browser receives. Validate external data when the application's behavior depends on its shape.

The build uses a small source tree and pinned compatible Angular, TypeScript and Node releases. The Angular compatibility table lists which major/minor versions work together. A package install that fails because a selected TypeScript major is unsupported does not need an Nginx workaround. Align the toolchain first. This exercise uses the project-local CLI installed with the rest of the packages. That lets the package resolution refer to the chosen version without requiring a globally installed ng binary.

Read outputPath and the selected builder, then open the actual build output. With the application builder here, the base output is dist/dairy-angular. The public artifact has an entry HTML file and its browser assets under the browser directory. This is a result of this builder and configured output, not a rule that follows solely from the Angular version. An older builder or an explicit browser output subpath can differ. A project that exports a server bundle or prebuilt route files can also write more than this fixture does. A working static deployment points Nginx at the intended browser artifact, and no private config or server package becomes a public URL.

Imagine copying dist/dairy-angular as the public root when the desired document lives one level deeper. Nginx might return 404 at the base path or find a different entry file. A reviewer can read the actual selected root and inspect the built HTML. Find the entry point it references and request that asset by the same URL a browser would use. Do not infer success from the output folder name, a successful build command or a directory listing without probing the running server. A built app can still point its scripts at the wrong public address.

DecisionThis project's choiceEvidence to collect
Source entryStandalone Angular bootstrap in TypeScriptCLI build used the selected application and compiled templates
RenderingClient-side only for both known routesPublic files include the entry and browser assets, with no frontend render service required by this example
StorageSame existing Express API and MongoDB fixtureCreate and reread the same confirmed ID through the edge and direct API
Static boundaryNginx maps the exact browser directoryReferenced script and stylesheet match built bytes; source and private files do not resolve

Connect the server's paths and the router's paths

Angular's router decides which component to display for the browser's navigation state. An Angular route configuration can map an empty path to a board overview and board/recent to a recent-notes view. The active view appears inside a router outlet, which is a placeholder where the router inserts the selected component. A RouterLink can navigate within a running app without asking for an entirely new HTML document. Arriving directly at the URL or refreshing a bookmark is different. The browser first requests that path from the HTTP server, where Angular's code is not yet executing.

Both listed page URLs should receive the generated index. Then the router selects the route according to its configuration. The <base href="/"> in this project's HTML declares the base for the root-mounted app. For a subpath deployment, adjust the generated base and Nginx public routing for that mount point, then check the exact URLs referenced in the HTML. The API may still intentionally live at /api/ for the whole origin. Don't append the Angular base to the API path by habit. The backend contract and asset URL design are different decisions.

The same server receives requests for public HTML, compiled bundles, and JSON notes. The static files built here include names in the root of the browser output. The older page's assumption that an Angular project never puts files under /assets/ would be too broad. Assets and their URLs come from the actual configuration. This exercise reads the generated script and style paths and verifies them. Nginx forwards the dedicated API prefix to the private shared service. A missing asset must have an ordinary edge 404. A missing API route should return the backend's error. Neither outcome should get the HTML entry for the Angular page.

Keep exact visible tests for each type of path. For example, the browser URL /board/recent should open a recent-note heading after the application starts. A generated style URL should return a stylesheet, regardless of which board route the user opened. The API list should return the expected JSON, and a nonexistent backend route should still produce an application JSON error. Checking these four requests separately will tell you whether a broken UI depends on Angular source code, the chosen artifact root, browser routing or the private application path.

Lab: compile the Angular board for its intended browser directory

Perform Steps 1 and 2 of the private Notes API lab. Start a fresh fixture from an ordinary-user Bash session and keep that shell open. Stop after Step 2 defines notes_url. This exercise uses the exact same private API and database as the React board. You do not need to replace any React setup on a running host. Use the required Node and npm versions for the Angular version indicated below, and have an Nginx executable. The Angular listener is a separate loopback port, 18906 by default, configurable through ANGULAR_EDGE_PORT. Its output and configuration stay inside this run's temporary folder.

Step 1. Define a small private workspace and the browser artifact

nginx_bin=${NGINX_BIN:-$(command -v nginx || true)}
test -x "$nginx_bin"
curl --noproxy '*' --fail --silent --show-error "$notes_url/api/ready"
angular_port=${ANGULAR_EDGE_PORT:-18906}
test "$angular_port" != "$notes_api_port"
angular_root="$notes_lab/angular"
nginx_pid=
angular_cleanup() {
  stop_notes_child "$nginx_pid"
  notes_cleanup
}
trap angular_cleanup EXIT
mkdir -p "$angular_root/src" "$angular_root/logs"

cat > "$angular_root/package.json" <<'JSON'
{
  "name": "private-dairy-angular-board",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": { "build": "ng build dairy-angular" },
  "dependencies": {
    "@angular/common": "22.3.0",
    "@angular/compiler": "22.3.0",
    "@angular/core": "22.3.0",
    "@angular/forms": "22.3.0",
    "@angular/platform-browser": "22.3.0",
    "@angular/router": "22.3.0",
    "rxjs": "7.8.2",
    "tslib": "2.8.1"
  },
  "devDependencies": {
    "@angular/build": "22.3.0",
    "@angular/cli": "22.3.0",
    "@angular/compiler-cli": "22.3.0",
    "typescript": "6.0.3"
  }
}
JSON
cat > "$angular_root/angular.json" <<'JSON'
{
  "version": 1,
  "cli": { "analytics": false, "cache": { "enabled": false } },
  "projects": {
    "dairy-angular": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular/build:application",
          "options": {
            "browser": "src/main.ts",
            "index": "src/index.html",
            "tsConfig": "tsconfig.app.json",
            "outputPath": "dist/dairy-angular",
            "outputHashing": "all",
            "ssr": false,
            "optimization": {
              "scripts": true,
              "styles": { "minify": true, "inlineCritical": false },
              "fonts": false
            },
            "styles": ["src/styles.css"]
          }
        }
      }
    }
  }
}
JSON
cat > "$angular_root/tsconfig.app.json" <<'JSON'
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "experimentalDecorators": true,
    "strict": true,
    "skipLibCheck": true
  },
  "angularCompilerOptions": { "strictTemplates": true },
  "files": ["src/main.ts"]
}
JSON
cat > "$angular_root/src/index.html" <<'HTML'
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mauli Dairy Angular board</title>
  </head>
  <body><app-root></app-root></body>
</html>
HTML
cat > "$angular_root/src/styles.css" <<'CSS'
:root { color: #172941; background: #faf7f0; font: 1rem/1.55 system-ui, sans-serif; }
body { margin: 0; }
main { max-width: 40rem; margin: 0 auto; padding: 1.5rem; }
nav { display: flex; flex-wrap: wrap; gap: 1rem; }
form { display: grid; gap: .5rem; max-width: 25rem; }
input, button { padding: .5rem; font: inherit; }
button { width: fit-content; }
li { overflow-wrap: anywhere; }
CSS

The workspace selects a browser entry, unprefixed by any public subfolder, and assigns an explicit output base. Its CLI options are settings for this disposable project. They do not change Angular settings in other workspaces. Note the build pinning also applies to the Angular compiler and local TypeScript release. Turning a compatible source into a working project involves the correct compiler flags and template checking, not only installing packages whose names say Angular. Node runs at build time and in the separate API process. This frontend does not require another Node service for rendering.

Step 2. Build the component, router and HTTP client

cat > "$angular_root/src/note-result.ts" <<'TS'
export interface Note { _id: string; text: string; }

export function expectNote(value: unknown): Note {
  if (value === null || typeof value !== 'object') throw new Error('Expected note object');
  const record = value as Record<string, unknown>;
  if (typeof record['_id'] !== 'string' || typeof record['text'] !== 'string') {
    throw new Error('Expected note fields');
  }
  return { _id: record['_id'], text: record['text'] };
}

export function expectNotes(value: unknown): Note[] {
  if (!Array.isArray(value)) throw new Error('Expected note list');
  return value.map(expectNote);
}
TS
cat > "$angular_root/src/main.ts" <<'TS'
import { Component, Injectable, inject, signal, type OnInit } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, RouterLink, RouterOutlet, provideRouter } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { expectNote, expectNotes, type Note } from './note-result';

@Injectable({ providedIn: 'root' })
class NotesClient {
  private readonly http = inject(HttpClient);

  async list(): Promise<Note[]> {
    const body = await firstValueFrom(this.http.get<unknown>('/api/notes'));
    return expectNotes(body);
  }

  async add(text: string): Promise<Note> {
    const response = await firstValueFrom(
      this.http.post<unknown>('/api/notes', { text }, { observe: 'response' })
    );
    if (response.status !== 201) throw new Error('Expected created resource');
    return expectNote(response.body);
  }
}

@Component({
  selector: 'dairy-board',
  imports: [FormsModule],
  template: `
    <h1>{{ title }}</h1>
    <form (ngSubmit)="submit()">
      <label for="note-draft">Receiving note</label>
      <input id="note-draft" name="note" [ngModel]="draft()"
        (ngModelChange)="draft.set($event)" maxlength="200" [disabled]="saving()">
      <button type="submit" [disabled]="loading() || saving() || !draft().trim()">Add note</button>
    </form>
    <p role="status">{{ status() }}</p>
    <ul aria-label="Delivery notes">
      @for (entry of notes(); track entry._id) { <li>{{ entry.text }}</li> }
    </ul>
  `,
})
class Board implements OnInit {
  private readonly client = inject(NotesClient);
  readonly title = inject(ActivatedRoute).snapshot.data['title'] as string;
  readonly notes = signal<Note[]>([]);
  readonly draft = signal('');
  readonly loading = signal(true);
  readonly saving = signal(false);
  readonly status = signal('Loading notes…');

  ngOnInit(): void {
    void this.load();
  }

  private async load(): Promise<void> {
    try {
      const records = await this.client.list();
      this.notes.set(records);
      this.status.set(records.length ? 'Notes loaded.' : 'No notes yet.');
    } catch {
      this.status.set('Notes could not be loaded. Try reloading.');
    } finally {
      this.loading.set(false);
    }
  }

  async submit(): Promise<void> {
    const text = this.draft().trim();
    if (!text || this.loading() || this.saving()) return;
    this.saving.set(true);
    this.status.set('Saving note…');
    try {
      const note = await this.client.add(text);
      this.notes.update(records => [note, ...records].slice(0, 20));
      this.draft.set('');
      this.status.set('Note added.');
    } catch {
      this.status.set('The save could not be confirmed. Check the board before retrying.');
    } finally {
      this.saving.set(false);
    }
  }
}

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <main>
      <nav aria-label="Board pages">
        <a routerLink="/">Board home</a>
        <a routerLink="/board/recent">Recent board</a>
      </nav>
      <router-outlet />
    </main>
  `,
})
class App {}

bootstrapApplication(App, {
  providers: [
    provideHttpClient(),
    provideRouter([
      { path: '', pathMatch: 'full', component: Board, data: { title: 'Mauli Dairy Angular board' } },
      { path: 'board/recent', component: Board, data: { title: 'Recent receiving notes' } },
    ]),
  ],
}).catch(error => console.error(error));
TS
npm --prefix "$angular_root" install --ignore-scripts
npm --prefix "$angular_root" run build
browser_root="$angular_root/dist/dairy-angular/browser"
test -f "$browser_root/index.html"
printf 'Browser artifact: %s\n' "$browser_root"

This code provides the HTTP client once when bootstrapping the application. Dependency injection lets Angular give a component or service the object it needs, such as NotesClient, without the component manually constructing its dependencies. The request method returns an observable, which represents work that can produce values over time. These HTTP calls expect a single result. firstValueFrom turns that one result or error into a promise the example can await. The list method treats the received body as unknown until a runtime check verifies it. A TypeScript type supplied at build time alone cannot check bytes coming from the server.

Signals are reactive values used by the template. The component reads them when it renders and updates them when the database-backed call completes. During the initial request it disables the Add button and shows loading. During a POST the input is kept in place until the backend confirms a note. The draft gets cleared after confirmation. The note list keys each element with the ID the server generated. If the backend response is rejected, the screen tells the clerk the result could not be confirmed rather than making up an ID or showing a false success.

Both Angular paths use the same component and API service. The title data in each route gives its component a visible purpose after it mounts. The UI needs an explicit copy of the notes after navigating because this simple screen reads from the API when it initializes. Additional designs could share caching or client state deliberately. Do not infer that superficial differences in route labels justify storing a second database copy.

Serve the generated index and verify its exact dependencies

Step 3. Create an isolated Nginx route for the browser output

cat > "$angular_root/nginx.conf" <<NGINX
worker_processes 1;
pid "$angular_root/nginx.pid";
error_log "$angular_root/logs/error.log" notice;
events { worker_connections 64; }
http {
    types { text/html html; application/javascript js; text/css css; }
    access_log "$angular_root/logs/access.log";
    server {
        listen 127.0.0.1:$angular_port;
        server_name localhost;
        root "$browser_root";

        location = / { try_files /index.html =404; add_header Cache-Control "no-cache"; }
        location = /board/recent { try_files /index.html =404; add_header Cache-Control "no-cache"; }
        location = /index.html { try_files \$uri =404; add_header Cache-Control "no-cache"; }
        location ^~ /api/ { proxy_pass http://127.0.0.1:$notes_api_port; }
        location ~ "^/(main|styles|chunk|polyfills)-[A-Z0-9]+\.(js|css)$" {
            try_files \$uri =404;
            add_header Cache-Control "public, max-age=31536000, immutable";
        }
        location / { return 404; }
    }
}
NGINX
"$nginx_bin" -t -p "$angular_root/" -c "$angular_root/nginx.conf"
"$nginx_bin" -p "$angular_root/" -c "$angular_root/nginx.conf" -g 'daemon off;' &
nginx_pid=$!
for attempt in $(seq 1 40); do
  if test -s "$angular_root/nginx.pid"; then break; fi
  if ! kill -0 "$nginx_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
test "$(tr -d '[:space:]' < "$angular_root/nginx.pid")" = "$nginx_pid"
angular_url="http://127.0.0.1:$angular_port"
printf 'Local Angular board: %s/board/recent\n' "$angular_url"

Choose the root recorded by the successful build and keep the private Nginx configuration separate from global files. The page routes are exact in this exercise. The API prefix preserves the path Express expects. The pattern for static resources is chosen to match the known root-level hashed filenames this specific build produces. Don't use this one pattern as a general Angular config. A real project's asset URLs and hashes should drive its file and cache mapping. This lab checks that class before giving a long cache lifetime to hashed assets. A missing asset still gets 404 rather than the entry document.

Compare it with the React deployment. The API destination and path stay the same. Both known navigation routes depend on Nginx returning the client entry. The exact artifact directory and asset locations differ because the tools generate different layouts. You can run both boards in separate local environments or configure different hostnames in an authorized deployment. Do not remove an existing site's config to make room for another project without understanding its traffic. For this private test the Nginx process binds only the learner's own loopback port, and the start guard compares the process ID with the fixture's PID file.

Step 4. Read the public entry and check its JavaScript and CSS references

angular_request() {
  local path=$1 expected=$2 actual
  actual=$(curl --noproxy '*' --silent --show-error --max-time 8 \
    -D "$angular_root/headers" -o "$angular_root/body" -w '%{http_code}' \
    "$angular_url$path")
  printf '%s %s\n' "$actual" "$path"
  test "$actual" = "$expected"
}
python3 - "$browser_root/index.html" > "$angular_root/assets.txt" <<'PY'
from html.parser import HTMLParser
from pathlib import Path
import re, sys
from urllib.parse import urljoin

class Entries(HTMLParser):
    def __init__(self):
        super().__init__()
        self.entries = []
        self.base = None
    def handle_starttag(self, tag, attrs):
        fields = dict(attrs)
        if tag == "base":
            self.base = fields["href"]
        if tag == "script" and fields.get("type") == "module":
            self.entries.append(fields["src"])
        if tag == "link" and fields.get("rel") == "stylesheet":
            self.entries.append(fields["href"])

contents = Entries()
contents.feed(Path(sys.argv[1]).read_text())
assert contents.base == "/", contents.base
names = [urljoin(contents.base, entry) for entry in contents.entries]
assert any(path.endswith(".js") for path in names), names
assert any(path.endswith(".css") for path in names), names
for name in names:
    assert re.fullmatch(r"/(main|styles|chunk|polyfills)-[A-Z0-9]+\.(js|css)", name), name
    print(name)
PY
angular_request / 200
cmp "$angular_root/body" "$browser_root/index.html"
grep -qi '^Cache-Control: no-cache' "$angular_root/headers"
angular_request /board/recent 200
cmp "$angular_root/body" "$browser_root/index.html"
while IFS= read -r path; do
  angular_request "$path" 200
  cmp "$angular_root/body" "$browser_root$path"
  case "$path" in
    *.js) grep -qi '^Content-Type: application/javascript' "$angular_root/headers" ;;
    *.css) grep -qi '^Content-Type: text/css' "$angular_root/headers" ;;
  esac
  grep -qi '^Cache-Control: .*immutable' "$angular_root/headers"
done < "$angular_root/assets.txt"
angular_request /main-MISSING.js 404
if grep -qi '^Cache-Control: .*immutable' "$angular_root/headers"; then exit 1; fi
angular_request /board/no-such-view 404
angular_request /angular.json 404
angular_request /src/main.ts 404
angular_request /api/not-a-route 404
grep -qi '^Content-Type: application/json' "$angular_root/headers"
grep -Fq 'unknown route' "$angular_root/body"

The Python helper reads the produced HTML as a document, rather than using an old bundle name. It identifies module scripts and external stylesheets and checks that the base is the root. Each file then has to resolve from the edge with exactly the bytes created by the compiler. Test the stylesheet as well as the main module. An unstyled initialized page and a browser that never ran Angular can look different to the visitor and have different causes. The missing-file, unknown-navigation and API-negative cases verify that these path families don't collapse into one result.

You can now connect the deployment evidence to the build. The root contains the public index and browser assets. An ordinary public request doesn't return the source workspace configuration. The direct recent route returns the correct entry. The client router will supply its heading once the compiled app mounts. The command-line check doesn't execute Angular in a browser. A separate interactive check below makes that visible. Keep the browser interpretation distinct from the simpler evidence about file delivery.

Compare the same data shape from Angular's public and private paths

Step 5. Drive the real API and test the response parsing

cat > "$angular_root/verify-results.mts" <<'TS'
import assert from 'node:assert/strict';
import { expectNote, expectNotes } from './src/note-result.ts';

const [edge, api] = process.argv.slice(2);
const list = async (origin: string) => {
  const reply = await fetch(new URL('/api/notes', origin), { cache: 'no-store' });
  assert.equal(reply.status, 200);
  return expectNotes(await reply.json());
};
assert.deepEqual(await list(edge), []);
const posted = await fetch(new URL('/api/notes', edge), {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ text: 'Receiving shift checked' }),
});
assert.equal(posted.status, 201);
const note = expectNote(await posted.json());
assert.match(note._id, /^[0-9a-f]{24}$/);
assert.equal(note.text, 'Receiving shift checked');
assert.equal(posted.headers.get('location'), '/api/notes/' + note._id);
assert.deepEqual(await list(edge), [note]);
assert.deepEqual(await list(api), [note]);
assert.throws(() => expectNotes({ error: 'unexpected' }), /Expected note list/);
assert.throws(() => expectNote({ _id: 7, text: 'wrong ID type' }), /Expected note fields/);
console.log('Angular note validators and real edge/API agree:', note._id);
TS
node "$angular_root/verify-results.mts" "$angular_url" "$notes_url"

This checker imports the exact runtime validation functions used by the Angular app but invokes the HTTP requests from Node. Node 24 can run this script's erasable TypeScript syntax. This does not run Angular dependency injection or templates outside the browser. It proves the data and validation behavior behind both edge and backend addresses. The ID in the Location header gives you another way to identify the one stored record. The two simulated wrong shapes demonstrate that a TypeScript type declaration on its own would not make a response match the contract.

Open the printed board URL in a local browser before cleanup for the interactive check. The path should produce the heading “Recent receiving notes” and the seeded “Receiving shift checked” item. Follow Board home and Recent board using the router links. The heading should change and the simple route view should load the same list. In the Receiving note field enter “Evening stock counted” and choose Add note. Wait for confirmation before reloading the deep URL. The list should contain both notes. Check the network panel for a GET after reload and the earlier POST with a 201 result. Watch the status region during the request and verify the input remains usable by keyboard.

Step 6. Keep the statics available through a deliberate database pause

stop_notes_child "$db_pid"
db_pid=
angular_request /board/recent 200
cmp "$angular_root/body" "$browser_root/index.html"
angular_request /api/health 200
angular_request /api/notes 503
grep -Fq 'notes temporarily unavailable' "$angular_root/body"
start_notes_db
for attempt in $(seq 1 20); do
  if angular_request /api/ready 200; then break; fi
  sleep 0.25
done
grep -Fq '"storageResponding":true' "$angular_root/body"
angular_request /api/notes 200
grep -Fq 'Receiving shift checked' "$angular_root/body"
angular_cleanup
trap - EXIT
test ! -e "$notes_lab"
printf 'Private Angular board and shared API removed.\n'

The Angular index remains accessible during the database stop, so a correct interface can still show a request-level error. The backed route returns the error body from the shared API. The app doesn't redesign or recompile itself due to a temporary database fault. Restoring the same data files makes the previously added note visible again. Once done, cleanup stops the private listener and delegates API and database cleanup to the earlier exercise. Its tested data and packages were all in one temporary tree.

Write down what would convince another maintainer the build works

A maintainer who didn't build this project needs enough detail to reproduce its path. Start a short record with the chosen Angular and builder versions, frontend render mode, base path, output directory and local Nginx origin. Record the API origin only in your private lab report where appropriate. That information helps the reviewer understand whether they should expect a client package, a server runtime or a combination. Give each verification a concrete question. “Page looked good” is less useful than “recent URL returned the exact built index, which referred to these generated assets, and the browser then loaded its route heading.”

For example, an output under your temporary workspace might contain a script named main-ABCD1234.js and a stylesheet named styles-EFGH5678.css. The hashes here are illustrative. Read your actual names instead. A direct attempt at /board/recent should get the same entry as the root path. The named JavaScript should return bytes identical to the actual output file. The stylesheet should also match and carry a CSS media type. This checks deployment paths, even though it doesn't yet test the Angular component. Try a bogus filename of the same class too. An error that is cached as immutable could make later diagnosis or recovery more confusing.

Next compare the result of a private API read and the public-shaped route. Start from a clean fixture. The initial public result is a successful empty array. Create “Receiving shift checked,” read the ID, and compare the note as returned through both paths. The presence of the same ID from the independent backend request demonstrates that you didn't merely set a local form field or replay a fixture response in the browser. The helper checks the application response's selected fields. The former Notes API lesson separately asserts that the database itself persists the expected types. Taken together, these checks let a reviewer connect the deployment to the trusted data path.

A clearly defined browser check complements those results. In the receiving board, the route heading proves the app actually mounted and chose the expected route. Use the keyboard to move from the navigation to the input and button. Enter text that differs from the seeded note so the result is easy to find. Record how the app communicates loading and confirmation using the visible text. After refreshing the deep link, the browser should request a new list and render the same saved text. A click that updates the browser visually without the backend response does not satisfy this expectation. The network and direct API evidence should match the interactive outcome.

Record one negative condition that shows why your verified path matters. The supplied experiment keeps the compiled page available during deliberate storage failure. The UI should be capable of rendering an error state because its JavaScript is still served. The proxied list produces an HTTP 503. This is different from a byte comparison failure for the built module or a wrong Content-Type on an API URL. Pick remediation based on that distinction. If you fix an upstream issue and the public app begins returning data, check the recovered note ID to prove you still reach the same intended database.

Suppose you plan to roll this out next to the React board on one server. The two builds can be served by separate site configurations and distinct hostnames or well-defined paths. Agree whether both call the same API origin through their web entry points, then test each as that client. Do not copy one configuration and remove it by filename as a routine first step. The prior site might still have working users or different routes. A rehearsal should test both the candidate and existing control site along with the retention policy for static outputs. Explicit ownership and checks make a migration reversible.

For a bundle that uses additional paths or lazy route chunks, make those decisions visible. Inspect their URLs in a real browser when opening every affected route, as the HTML only lists its initial dependencies. Build output can refer to chunks later. A routing rule that covers the entry module but rejects a lazy-loaded file may pass a shallow home check and fail in a later interaction. Give each documented route an acceptance step that actually reaches its content. Use the deployed files as the source of truth for which static URLs are intended, and deliberately handle unknown paths.

When you share these notes with a classmate, say which part was tested and which part still needs a browser. A build, its served bytes, a runtime data probe and a UI interaction provide different evidence. A complex deployment can legitimately fail at just one of those boundaries. A reproducible record makes it possible to repeat the specific missing test rather than guessing that recalculating a build cleared the issue.

Follow one input through the Angular form and back to its template

Start with a newly opened receiving-board route. The router creates the component and supplies the route's title. The component exposes an initially empty notes signal, but it does not yet know whether the database has zero notes. It shows “Loading notes…” while the HTTP service starts the list request. The service requests a response from a known path and passes the received value to expectNotes. This function accepts the actual array only if every entry has the required string fields. A successful empty array makes “No notes yet” meaningful. An API outage or an HTML response fails differently and produces the load-error message.

A signal is read through its getter-like function in this template. Updates to the signal inform Angular which parts of the displayed view depend on it. Setting the notes signal after the request changes the displayed list. The @for loop uses the unique ID as a tracking key so Angular can recognize the same note when the array changes. Tracking by a mutable display field, such as the note text, would make editing the same resource look like an entirely new list item. Using the API's stable ID reflects the application's data model and keeps it distinct from the screen label.

Now enter “Evening stock counted.” The input change writes the draft signal. The button expression allows submission only for a nonblank draft when loading and saving have finished. This is a convenience and feedback rule in the interface. The backend still validates string shape and length on every request. When Angular's form submits, the component sends the chosen text through the injected service. The submit state becomes busy, and the input stays populated while the answer is still unknown. The HTTP helper returns the response wrapper on creation so the code can verify it got 201, as the contract requires. It then extracts the created note's ID and text.

If the backend stored the note, it returns that created representation and the component prepends it. The note now appears in the visible list. If Nginx cannot find the API, a non-success response moves through the request's error path. If there was a successful-looking response with an unexpected shape, the runtime validator throws. In both cases the draft is kept for the user's next decision. The application cannot always infer whether an unconfirmed POST reached storage. A reload or direct lookup can reconcile the state before blindly retrying. The server's expected input keys are documented in the shared API lesson.

A user can open another route while an old request is still pending. This small app creates a new board at each of its distinct route configurations. A richer app should plan whether changes in router state cancel obsolete requests or preserve a shared cached list between routes. Angular's HTTP observable lets a client cancel a request by unsubscribing. The one-shot promise helper in this exercise keeps a learning example simple and avoids continuous subscriptions. If you need stronger cancellation, use an observable lifetime tied to the component or another documented mechanism. Keep API events and state transitions visible in the expected test, rather than assuming they all happen synchronously when the component is displayed.

Choose the output model with the route's requirements in mind

Compare the receiving board with a public dairy description page. The board is an interactive work screen; its current notes are fetched after startup. Serving its client artifact can make an appropriate training deployment without adding a frontend rendering service. A stable public page might be prerendered so its full content exists in the generated HTML when the visitor arrives. A request-dependent route with custom page state could instead use server-side rendering to send an initial representation at request time. The browser can then run JavaScript and attach interaction to the rendered content. Angular calls this hydration in supported rendering setups. Each choice changes what must be deployed and tested.

Prerendering computes content at build time. If that content includes a value that is supposed to be current for each visitor, a static precomputed copy can go stale unless the site refreshes it or asks for live data later. Server-side rendering computes content while handling an HTTP request, so it needs an active renderer in a supported host environment. A project can combine the modes for different paths. Read its route rendering configuration and build output before setting any Nginx root. A browser directory can contain the files used by visitors alongside a separate server directory that belongs behind a runtime boundary.

Suppose you inherit a workspace that says “Angular 22” but it puts the frontend under dist/site/public. The Angular version doesn't force a fixed folder. Inspect the workspace's builder options, especially the configurable base and browser parts of the output path. Confirm whether the page is a basic client entry or a collection of generated pages. A command-line test that follows the loaded HTML's actual script and style URLs remains useful across choices. For a server-rendered route, add a test that verifies the initial HTML contains the intended content and checks what the browser does after it becomes interactive.

Think about build-time and request-time configuration separately. The router and public API path are information a browser can know. A setting in a source file or built replacement bundle is available to visitors who download it. Keep passwords, service tokens and private database connection settings in the trusted backend. If a frontend renderer uses separate private server settings, choose which values, if any, appear in the HTML and browser state. The build mode doesn't automatically make information safe just because a project has both browser and server folders.

Consider the receiving board's data requirements before prerendering. It should display current work and may eventually show restricted records. If you fetch real records while building a static page and embed their text in its HTML, ordinary users who receive those files may see the embedded data regardless of a later client-side login display. The more appropriate boundary depends on the route and intended audience. The lab asks the API for notes only after startup. A deployed authenticated screen still needs the API to enforce that request's permissions. Inspect both the generated HTML and runtime response data when adding private features.

When deploying under /staff/ instead of this lesson's root, walk through an example with actual values. A user bookmarks /staff/board/recent. Nginx must return the intended entry for that navigation path. A relative build resource such as main-ABCD.js should be resolved using the configured public base. The Angular router must understand which part of the path belongs to the mount point. A same-origin absolute API request to /api/notes can remain outside /staff/ if that route is the agreed service entry. Test each URL as the browser sees it and compare to the working backend without carrying old assumptions from a root deployment.

Use the failure pattern to identify the responsible layer

Suppose a colleague opens the home document and the browser tab has the correct title, but there is no Angular board. The title comes from the generated HTML. Check the exact asset named in it, its content type and whether its content matches release bytes. Then open the browser console to see whether Angular initialized and verify the app-root element exists. A component missing a provider can fail after the correct script downloads. An HTTP test doesn't create components, so use a browser assertion for that result. The workflow is to confirm the earliest failing observation.

Now imagine a user reaches Recent board using the router link, but refresh at the same URL returns 404. A successful in-app navigation proves the router and frontend code knew a path after loading. The refresh asks the HTTP server for that path directly. Compare which location rule handles it and whether the public base and prefix match. In this private lab the two known browser paths map to the same index explicitly. Treat a private missing-link error as a mapping defect first and retain the separate test that a genuinely unknown navigation gets 404.

If the notes fail only after someone moves the API proxy, compare /api/not-a-route and /api/notes through Nginx with the same paths directly to Express. An expected backend JSON error indicates which program received the prefix. A 200 HTML document is evidence of the wrong rule if the request expected a JSON list. An application 503 during the controlled pause shows the API reached its dependency logic while the browser bundle remains valid. The same words on the screen are not enough to identify the first failure. Record the HTTP statuses, bodies and intended route in your diagnosis.

Finally, consider an inconsistent asset release. The deployed HTML points at a new CSS file, but the server still uses the previous browser folder. The site may look broken even if notes can still load from the old bundle. Confirm each generated asset is ready before activating a new entry document and retain versioned assets where existing HTML or open browsers can reference them. Roll back to a known coherent set if needed, and retest the direct link, actual JS, stylesheet and one note read. Careful release boundaries are as important as selecting a build command.

Review the decisions and evidence with a teammate

Interview answers

What tells you which Angular directory to serve?

Read the configured builder and output path, then inspect the generated index and assets. In this specific browser-only application builder example the files are under dist/dairy-angular/browser. Another builder, customized output, or a hybrid render setup can change what is publicly served and whether a runtime is needed.

Why do Angular's TypeScript annotations not replace response validation?

The JavaScript the browser runs receives bytes parsed from an HTTP response. It still needs to ensure the received value is an array or record with the expected fields. A type used during compilation offers information to the developer and compiler. The runtime guard catches malformed data and wrong-route responses at the actual application boundary.

How does this Angular board use the same backend as the React board?

Both call /api/notes with the same GET and POST contract. Nginx forwards that path to the existing Express service. The Angular view can use its own services and templates while keeping the response ID, input field names and persistence behavior unchanged.

Why can an in-app click work while opening the same route directly fails?

The running router handles a click inside the app. A direct navigation or reload first asks the HTTP server. Client-rendered routes require the intended server mapping to deliver the entry before the router runs. Build paths, browser base and server locations must describe the same URL layout.

Quick quiz

Which files should this private Nginx root serve: the workspace, the entire base output, or the built browser directory?

The built browser directory for this project. It has the actual entry and generated browser bundles. Packages, source and potential server artifacts remain outside the publicly mapped root.

The Express API reports 503 but Angular's bundle still loads. Should a frontend rebuild be the first fix?

Investigate the backend and its dependency. The asset and HTML still respond with their expected bytes. The API is alive but cannot perform the note lookup. A rebuild would change a different layer.

Should the component clear the draft before the database-backed POST is confirmed?

Keep it until confirmation. If there is no verified created result, the user needs the draft and a clear failure message. On success use the returned ID rather than generating a pretend record locally.

Practice tasks

  1. Find the runtime base, JavaScript and CSS references in the built Angular index. Verify each reference goes to the intended URL and returns the matching bytes through Nginx. Compare them with the React lesson's separate build.
  2. In a browser try Board home and Recent board, then reload the direct recent URL and observe the same data after adding a note. Record the point at which the browser requested HTML versus the point at which it requested JSON.
  3. Sketch a future version with one prerendered public page and another route using server rendering. List which outputs may be public and which process or backend must run for the request-dependent page.

Builder selects output shape

Inspect workspace settings and the generated entry before choosing Nginx's root.

Router has a browser lifetime

Opening a deep URL directly requires the entry from the HTTP server before Angular handles it.

Observe real input data

Check response fields at runtime and update the form and list only after meaningful HTTP results.

Same API, different interface

Angular and React can share methods, IDs and response fields without duplicating the notes database.

Official references