Anguar Parts 4 & 5
Angular Tutorial – Parts 4 & 5: From Patterns to Production
Learn advanced dependency injection, RxJS workflow choices, resilient API handling, HTTP testing, and how to prepare an Angular feature for release.
Part 4 — Advanced Angular Patterns
1Dependency Injection Tokens and Scopes
Injection tokens let Angular provide values that are not classes, such as feature configuration. A provider on a component is scoped to that component and its descendants; a root provider is shared application-wide.
import { InjectionToken, inject } from '@angular/core';
export interface CatalogConfig {
apiUrl: string;
}
export const CATALOG_CONFIG =
new InjectionToken<CatalogConfig>('CATALOG_CONFIG');
export function injectCatalogConfig() {
return inject(CATALOG_CONFIG);
}{
path: 'catalog',
providers: [
{ provide: CATALOG_CONFIG, useValue: { apiUrl: '/api/catalog' } }
],
loadComponent: () => import('./catalog-page.component')
.then(m => m.CatalogPageComponent)
}2Choose the Right RxJS Operator
Flattening operators define what happens when a new value arrives while earlier work is still running. Picking the right one prevents duplicate, stale or unexpectedly parallel requests.
| Operator | Use it when |
|---|---|
switchMap | Only the latest result matters, such as type-ahead search. |
concatMap | Every operation must run, in order, such as queued updates. |
mergeMap | Independent operations may run concurrently. |
exhaustMap | Ignore new triggers until the current operation finishes, such as blocking repeated submits. |
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
const results$ = searchControl.valueChanges.pipe(
debounceTime(250),
distinctUntilChanged(),
switchMap(query => catalogApi.search((query ?? '').trim()))
);3Resilient API Error Handling
Handle errors where the app can give useful feedback. Retrying a read request may be reasonable for transient network failures, but automatically retrying a create or payment request can duplicate a side effect.
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, of, retry, throwError, timer } from 'rxjs';
readonly products$ = this.http.get<Product[]>('/api/products').pipe(
retry({
count: 2,
delay: (error: HttpErrorResponse, attempt) =>
error.status === 0 || error.status >= 500
? timer(attempt * 500)
: throwError(() => error)
}),
catchError(error => {
this.logger.error('Unable to load products', error);
this.loadError.set('Products could not be loaded. Try again.');
return of([]);
})
);- Give users an actionable message and a way to retry when appropriate.
- Keep technical details in diagnostics; do not expose secrets or stack traces in the UI.
- Distinguish empty results from a failed request.
- Use idempotency controls on the server for operations that must not be duplicated.
4Test HTTP Services
Angular's HTTP testing utilities let a test inspect the outgoing request and provide a fake response without making a real network call.
import { TestBed } from '@angular/core/testing';
import {
provideHttpClient
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting
} from '@angular/common/http/testing';
import { CatalogApi } from './catalog.api';
describe('CatalogApi', () => {
let api: CatalogApi;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()]
});
api = TestBed.inject(CatalogApi);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('loads products from the catalog endpoint', () => {
api.getProducts().subscribe(products => {
expect(products.length).toBe(1);
expect(products[0].name).toBe('Keyboard');
});
const request = http.expectOne('/api/products');
expect(request.request.method).toBe('GET');
request.flush([{ id: 1, name: 'Keyboard' }]);
});
});provideHttpClient() before provideHttpClientTesting() so the test provider replaces the real backend.Part 5 — Build and Ship a Feature
5Build a Typed Feature API
Keep HTTP calls in a feature data service rather than scattering URLs through templates and components. Type the response shape and keep request methods explicit.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: number;
name: string;
price: number;
}
export type NewProduct = Pick<Product, 'name' | 'price'>;
@Injectable({ providedIn: 'root' })
export class CatalogApi {
private http = inject(HttpClient);
private readonly url = '/api/products';
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.url);
}
createProduct(input: NewProduct): Observable<Product> {
return this.http.post<Product>(this.url, input);
}
}TypeScript types improve development feedback; they do not validate untrusted server responses at runtime. Validate critical data at the API boundary when the application requires it.
6Design Complete UI States
A production feature should communicate what is happening, not just render data after success. Plan for loading, empty, error and ready states, and prevent accidental duplicate submissions.
In a standalone component, import CurrencyPipe to use the currency formatting in this template.
@if (loading()) {
<p role="status">Loading products...</p>
} @else if (error()) {
<p role="alert">{{ error() }}</p>
<button type="button" (click)="reload()">Try again</button>
} @else if (products().length === 0) {
<p>No products yet. Add your first product.</p>
} @else {
<ul>
@for (product of products(); track product.id) {
<li>{{ product.name }} — {{ product.price | currency }}</li>
}
</ul>
}Use status and alert roles thoughtfully so assistive technologies announce updates without making the page noisy.
7Automate Checks in CI
Run a consistent set of checks for every change. The exact test command can vary by Angular CLI version and project setup, so use the scripts already defined by your project.
npm ci
npm run lint
npm test -- --watch=false
npm run build -- --configuration production- Use a supported Node.js version and lockfile-based dependency installation.
- Fail the workflow when lint, tests or the production build fail.
- Keep deployment credentials in the CI provider's secret store, never in the repository.
- Build once and promote the same verified artifact between environments where possible.
8Prepare and Release the App
- Review production build output and address unexpected bundle growth.
- Configure the host to serve the Angular entry point for client-side routes.
- Use HTTPS and configure API access controls on the server.
- Check forms, keyboard navigation, error states and narrow-screen layouts.
- Monitor client and server errors after release, and prepare a rollback path.
🎉 Parts 4 & 5 complete! You have practiced advanced Angular patterns and taken a feature from implementation through release. — A143MK
No comments :
Post a Comment
Please Write a Message for Programming or something else 🙏